Basics and Core Concepts
-
What are JavaScript data types?
-
JavaScript has 7 primitive data types:
undefined,null,boolean,number,string,symbol, andbigint. Objects are non-primitive data types.
js// Primitive let name = "Ram"; // String let age = 25; // Number let isOnline = true; // Boolean let nothing = null; // Null let x; // Undefined let id = Symbol("id"); // Symbol let big = 12345678901234567890n; // BigInt // Non-Primitive let person = { name: "Ram" }; // Object let arr = [1, 2, 3]; // Array (object type) let func = function() {}; // Function (object type) -
- Evaluate 6 + "52" ?
"652"
-
What is the difference between
==and===?-
==compares values and performs type coercion, while===compares both values and types.
js1 == "1"; // true 1 === "1"; // false -
-
What is the difference between
nullandundefined?-
🔹
undefinedmeans "Value has not been assigned yet"🔹
nullmeans "Value is intentionally set to empty"
jslet a = null; // null -> value set to empty let b; // undefined -> value not given -
-
What is a closure?
-
A closure is a function that retains access to its lexical scope even after the function is executed outside that scope.
jsfunction outer() { const a = 10; return function inner() { console.log(a); }; } const closure = outer(); closure(); // Output: 10 -
-
What is a callback function?
-
A callback function is passed as an argument to another function and is executed after the completion of that function.
jsfunction greeting(name) {console.log("Hello, " + name+"(callback)");}function main(callback) {const name = "Alice";console.log("this is main function")callback(name); // calling the callback function}main(greeting) -
⚙️ Functions, Scope, and Execution Context
-
What is the difference between
var,let, andconst?-
varis function-scoped, whileletandconstare block-scoped.constcannot be reassigned.
jsvar x = 10; // function-scoped let y = 20; // block-scoped const z = 30; // block-scoped, read-only -
-
What is hoisting in JavaScript?
-
Hoisting is JavaScript's default behavior of moving declarations to the top of their containing scope during compile time.
jsconsole.log(x); // undefined var x = 5; -
-
What is an Arrow function?
-
An arrow function is a shorter and more concise way to write function expressions in JavaScript.It was introduced in ES6 and It improves readability and avoids
thisbinding issues
-
-
What is the
thiskeyword in JavaScript?-
In JavaScript, the
thiskeyword refers to the object that is executing the current function.But its value depends on how the function is called, not where it's written.
jsconst person = {name: "Sam",gender:"male",greet: function() {console.log("Hello, " + this.name);}};person.greet(); // Hello, Sam -
-
What is a higher-order function?
-
A higher-order function is one that takes another function as an argument or returns a function as a result.
js
Example 1 (Taking function as argument):function greet(name) { return "Hello, " + name; } function main(callback) { const name = "Sam"; console.log(callback(name)); } main(greet);
Example 2 (returns a function):
function multiplyBy(factor) { return function (number) { return number * factor; }; } const double = multiplyBy(2); console.log(double(5)); -
🔁 Arrays, Objects, and Iteration
-
What is the difference between
for...inandfor...of?-
for...initerates over keys (properties) of an object, whilefor...ofiterates over values in an iterable (like arrays).
jsconst arr = ["a", "b", "c"]; for (let index in arr) { console.log(index); // keys: 0, 1, 2 } for (let value of arr) { console.log(value); // values: "a", "b", "c" } -
-
What is the difference between shallow and deep copy?
-
🔹 Shallow Copy
A shallow copy copies only the first level of the object or array.
If the object has nested objects, they are still referenced, not copied.🔹 Deep Copy
A deep copy copies everything, including nested objects, so the copy is completely independent of the original.
jsconst original = {name: "Sam",address: {city: "Delhi",pin: 110001}};// 🔸 Shallow Copy using spreadconst shallowCopy = { ...original };// 🔹 Deep Copy using JSONconst deepCopy = JSON.parse(JSON.stringify(original));// Modify nested valueoriginal.address.city = "Mumbai";console.log(shallowCopy.address.city); //console.log(deepCopy.address.city); -
-
What is array destructuring?
-
Array destructuring allows unpacking values from arrays into distinct variables.
jsconst arr = [1, 2, 3]; const [first, second] = arr; console.log(first, second); // Output: 1, 2 -
-
How do you merge two arrays?
-
You can use the spread operator or
concat()to merge arrays.
const merged = arr1.concat(arr2); console.log(merged);jsExample using spread operator:const arr1 = [1, 2]; const arr2 = [3, 4]; const mergedArray = [...arr1, ...arr2];
Example using concat: -
-
How to filter an array?
-
Use the
filter()method to filter an array based on a condition.
jsconst numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); -
⏳ Promises, Async/Await, and Callbacks
-
What is a promise in JavaScript?
-
A Promise is a JavaScript object that represents the result of an asynchronous task like API calls, file reading, timers, etc.
jsconst promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Success"); } else { reject("Failure"); } }); -
-
What is async/await?
-
asyncfunctions return a promise, andawaitpauses the execution until the promise is resolved.
jsconst myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("✅ Operation Successful"); } else { reject("❌ Operation Failed"); } }); myPromise .then((result) => { console.log(result); // ✅ Operation Successful }) .catch((error) => { console.log(error); // ❌ Operation Failed }); -
-
How does
.then()and.catch()work?-
.then()is used to handle the success case, while.catch()is used to handle errors.
jsconst myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("✅ Task completed"); } else { reject("❌ Task failed"); } }); myPromise .then((result) => { console.log("Success:", result); }) .catch((error) => { console.log("Error:", error); }); -
-
What is promise chaining?
-
Promise chaining allows you to execute multiple asynchronous operations sequentially.
jsExample:function placeOrder() {return Promise.resolve("Order placed");}function prepareFood(status) {return Promise.resolve(`${status} → Food prepared`);}function deliverFood(status) {return Promise.resolve(`${status} → Food delivered`);}placeOrder().then(prepareFood).then(deliverFood).then((msg) => console.log("✅", msg)).catch((err) => console.log("❌ Error:", err)); -
-
What is the purpose of
finally()in promises?-
The
.finally()method is used to run some code after a promise is settled, no matter whether it was resolved (✅ success) or rejected (❌ error).
jsExample:const order = new Promise((resolve, reject) => { const success = true; if (success) { resolve("🍔 Order delivered"); } else { reject("❌ Order failed"); } }); order .then((msg) => { console.log("Success:", msg); }) .catch((err) => { console.log("Error:", err); }) .finally(() => { console.log("🔁 Done with order process (success or fail)"); }); -
🔄 Event Loop, Timers, and Concurrency
-
What is the event loop in JavaScript?
-
The event loop manages the execution of code, handling both synchronous and asynchronous operations.
-
-
What is the difference between microtasks and macrotasks?
-
Microtasks are executed after the current script has finished, but before rendering or IO tasks (e.g.,
Promise.then()), whereas macrotasks are handled by the event loop (e.g.,setTimeout()).
-
-
What is the purpose of
setTimeout()?-
setTimeout()schedules a function to run after a specified delay.
jssetTimeout(() => console.log("Delayed"), 1000); -
-
What is
setInterval()?-
setInterval()calls a function repeatedly at specified intervals.
jssetInterval(() => console.log("Repeated"), 2000); -
-
What is the
clearTimeout()andclearInterval()functions?-
clearTimeout()cancels a scheduledsetTimeout(), andclearInterval()cancels a scheduledsetInterval().
jssetTimeout:
const timeoutId = setTimeout(() => { console.log("This will not run"); }, 3000); // Cancel it clearTimeout(timeoutId);
setInterval:
const intervalId = setInterval(() => { console.log("Repeating every second"); }, 1000); // Stop it after 5 seconds setTimeout(() => { clearInterval(intervalId); console.log("Stopped the interval"); }, 5000); -
🧱 Classes, Inheritance, and Prototypes
-
What is prototypal inheritance?
-
Prototypal inheritance is when objects inherit properties and methods from other objects via their prototype chain.
js// Constructor function (like a blueprint)function Person(name) {this.name = name;}// Adding method to Person's prototypePerson.prototype.greet = function () {console.log("Hello, my name is " + this.name);};// Create a new object using Personconst personObj = new Person("Sam");personObj.greet(); -
-
How do you create a class in ES6?
-
ES6 classes provide a simpler syntax for creating constructor functions and prototypes.
js// Define a class class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound`); } } // Create an object from the class const dog = new Animal("Dog"); dog.speak(); -
-
What is inheritance in JavaScript?
-
Inheritance allows one class to extend another and reuse its properties and methods.
js// Parent class class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound`); } } // Child class class Dog extends Animal { bark() { console.log(`${this.name} barks 🐶`); } } // Create object const myDog = new Dog("Tommy"); myDog.speak(); // Tommy makes a sound (inherited from Animal) myDog.bark(); // Tommy barks 🐶 (defined in Dog) -
-
How does
super()work?-
super()is used inside a child class constructor to call the constructor or methods of the parent class.
js// Parent class class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound`); } } // Child class class Dog extends Animal { constructor(name, breed) { super(name); // Call parent constructor this.breed = breed; } info() { console.log(`${this.name} is a ${this.breed}`); } } const dog = new Dog("Tommy", "Labrador"); dog.speak(); // Tommy makes a sound (from Animal) dog.info(); // Tommy is a Labrador (from Dog) -
-
What is method overriding in JavaScript?
-
Method overriding occurs when a child class defines a method that is already defined in its parent class.
js// Parent classclass Animal {speak() {console.log("Animal makes a sound");}}// Child class overrides the speak methodclass Dog extends Animal {speak() {console.log("Dog barks");}}const dog = new Dog();dog.speak(); -
ES6+ Features
-
What is destructuring in JavaScript?
-
Destructuring allows you to unpack values from arrays or properties from objects into distinct variables.
jsconst person = { name: "John", age: 30 }; const { name, age } = person; // Object destructuring const [a, b] = [1, 2, 3]; // Array destructuring
-
What is the spread operator (
...)?
-
The spread operator is used to expand an iterable or object into individual elements or properties.
jsconst arr1 = [1, 2]; const arr2 = [...arr1, 3, 4]; const obj1 = { a: 1 }; const obj2 = { ...obj1, b: 2 };
-
What is the rest parameter (
...args)?
-
The rest parameter collects all remaining arguments into a single array.
jsfunction sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); } console.log(sum(1, 2, 3, 4)); // Output: 10
-
What is template literals?
-
Template literals provide an easy way to interpolate variables and expressions into strings.
jsconst name = "John"; const greeting = `Hello, ${name}`;
-
What is the
Mapobject?
-
The
Mapobject in javascript is a collection of key-value pairs like an object "{}", where both keys and values can be any data type.
jsconst myMap = new Map();// Set valuesmyMap.set("name", "Sam");myMap.set("ID number",123);myMap.set("Boolean", true);console.log(myMap.get("name")); // Samconsole.log(myMap.get("ID number")); // 123console.log(myMap.get("Boolean")); // trueconsole.log(Object.fromEntries(myMap)) // whole object
Modules and Import/Export
-
What is the difference between CommonJS and ES6 modules?
-
CommonJS uses
requireandmodule.exportsfor imports and exports, while ES6 usesimportandexport.
js// CommonJS const foo = require('./foo'); module.exports = foo; // ES6 import foo from './foo'; export default foo;
-
How to import/export specific members in ES6?
-
You can import and export specific members from modules using named exports.
js// foo.js export const foo = 1; export const bar = 2; // app.js import { foo, bar } from './foo';
-
What is dynamic import?
-
Dynamic import allows you to import a module asynchronously.
js// multiply.js export function multiply(a, b) { return a * b; }
// main.js // ✅ Dynamically import multiply.js and call multiply() import('./multiply.js').then(module => { const result = module.multiply(8, 5); console.log(`Result: ${result}`); }).catch(error => { console.error('Failed to load module:', error); });
-
What is
defaultexport?
-
A
defaultexport allows a module to export a single value, which can be imported without curly braces.
js// greet.js export default function greet() { console.log("Hello"); } // app.js import greet from './foo';
-
What is
export * from?
-
It re-exports everything from another module.
js
math.jsexport const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
allMath.jsexport * from './math.js'; // re-exports all functions
main.jsimport { add, multiply } from './allMath.js';
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
Error Handling and Debugging
-
How do you handle errors in JavaScript?
-
JavaScript provides
try...catchfor handling exceptions, andfinallyensures code runs after execution.
jstry { throw new Error("Something went wrong"); } catch (err) { console.error(err.message); } finally { console.log("Executed regardless of success or failure"); }
-
What is
throwin JavaScript?
-
The
throwstatement allows you to create custom errors.
jsthrow new Error("Custom error message");
-
What are custom errors?
-
You can create custom error classes by extending the built-in
Errorclass.
jsclass MyError extends Error { }try {throw new MyError("Hey Something went wrong!");} catch (err) {console.log("Caught:", err.message); //Output:Hey Something went wrong!}
-
What is
console.trace()used for?
-
console.trace()displays the stack trace, which is useful for debugging.
jsfunction foo() { console.trace("Stack trace"); } foo();
-
What is
debuggerin JavaScript?
-
The
debuggerkeyword pauses the execution of code, allowing you to inspect the state of the program.
jsfunction test() { debugger; // Execution stops here console.log("Hello"); } test();
Memory Management and Optimization
-
What is garbage collection in JavaScript?
-
JavaScript automatically manages memory by removing objects that are no longer reachable in the code.
-
What are closures and memory leaks?
-
Closures can sometimes result in memory leaks if they hold references to large objects even after they are no longer needed.
-
How to optimize memory usage in JavaScript?
Avoid unused variables
Don’t hold references unnecessarily
Use lazy-load for data and modules
Use efficient data structures like
Set,Map,WeakMap
-
What is a memory leak in JavaScript?
-
A memory leak happens when your program keeps storing data in memory that is no longer needed, and JavaScript’s garbage collector is unable to remove it — causing your app to use more and more memory over time.
Problem: bigData keeps growing and never gets cleared Result: Memory usage goes up, app becomes slow or crasheslet bigData = []; setInterval(() => { bigData.push(new Array(1000000).fill("💣")); // keeps growing }, 1000);
-
Which storage API stores data persistently?
-
localStorage
Performance Optimization
-
What is event delegation in JavaScript?
-
Event delegation means assigning an event listener to a parent element, and handling events for its child elements.
HTML<ul id="menu"><li>Home</li><li>About</li><li>Contact</li></ul><script>// ✅ Add one listener to the parentdocument.getElementById("menu").addEventListener("click", (event) => {if (event.target.tagName === "LI") {console.log("Clicked:", event.target.textContent);}});</script>
-
What is debouncing?
-
Debouncing limits the rate at which a function is executed, commonly used for search input fields or resize events.
HTML<input id="search" placeholder="Type..." /><script>function debounce(fn, delay) {let timeout;return (...args) => {clearTimeout(timeout);timeout = setTimeout(() => fn(...args), delay);};}const search = debounce((e) => {console.log("Search:", e.target.value);}, 500);document.getElementById("search").addEventListener("input", search);</script>
-
What is throttling?
-
Throttling ensures that a function is called at most once in a specified time period, even if it's triggered many times.
HTML<button id="btn">Click Me</button><script>function throttle(fn, delay) {let wait = false;return () => {if (!wait) {fn();wait = true;setTimeout(() => wait = false, delay);}};}document.getElementById("btn").onclick = throttle(() => {console.log("Clicked!");}, 5000); // 2 sec</script>
-
What is lazy loading in JavaScript?
-
Lazy loading involves loading resources or scripts only when they are needed to improve performance.
HTML<button id="load">Load Feature</button> <script type="module"> document.getElementById("load").onclick = async () => { const module = await import('data:text/javascript,export function greet(){ console.log("Hello from lazy-loaded code!"); }'); module.greet(); }; </script>
-
What is the difference between synchronous and asynchronous code?
-
Synchronous code is executed line by line, while asynchronous code allows functions to execute independently of the main program flow (using callbacks, promises, etc.).
-
What is an IIFE ?
-
IIFE (Immediately Invoked Function Expression) is a function that runs immediately after it’s defined.
js(function () { console.log("I am an IIFE!"); })();
-
How to create an immutable object in JavaScript
- We will use Object.freeze() to create an immutable object in JavaScript.
js// Normal (mutable) objectconst user1 = {name: "Ranit",age: 25};user1.age = 30;console.log("Mutable:", user1.age); // ✅ Output: 30//Immutable object using Object.freeze()const user2 = Object.freeze({name: "Amit",age: 28});user2.age = 35; // ❌ Change won't happenconsole.log("Immutable:", user2.age); // ✅ Output: 28
-
What is
localStorageandsessionStorage?
-
localStoragestores data with no expiration time, whilesessionStoragestores data for the duration of the page session.
-
What do you mean by Currying in JavaScript?
-
Currying is a technique where a function with multiple arguments is transformed into a series of functions, each taking one argument at a time.
js// Normal function function add(a, b) { return a + b; } console.log(add(2, 3)); // 5 // Currying version function curriedAdd(a) { return function (b) { return a + b; }; } console.log(curriedAdd(2)(3)); // ✅ Output: 5
-
What is Reduce() in javascript?
-
reduce()is a method used to combine all elements of an array into a single value, using a function that runs on each element one by one.jsconst numbers = [10, 20, 30]; const total = numbers.reduce((acc, curr) => { return acc + curr; }, 0); // initial value is 0 console.log(total); // Output: 60