JavaScript is a versatile and widely used programming language for web development. Whether you’re a beginner or an experienced developer preparing for interviews, understanding core JavaScript concepts is essential. In this article, we will explore fundamental JavaScript topics such as execution context, event loop, promises, closures, hoisting,
and more, with detailed explanations and examples to strengthen your knowledge.
1. What is ECMAScript in JavaScript?
ECMAScript (ES) is the standardized specification of JavaScript, maintained by TC39. It defines core features like syntax, types, operators, objects, and functions.
New versions (e.g., ES6, ES7, ES8) introduce modern features like let/const, arrow functions, async/await, and destructuring.
Example:
let name = "John"; // Introduced in ES6
const greet = () => console.log("Hello World!"); // Arrow function
greet();
2. Difference Between let
, const
, and var
Feature | var |
let |
const |
---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Hoisting | Yes, but initialized as undefined
|
Yes, but in Temporal Dead Zone (TDZ) | Yes, but in TDZ |
Reassignment | Yes | Yes | No |
Example:
var x = 10;
let y = 20;
const z = 30;
y = 50; // Allowed
z = 40; // Error: Assignment to constant variable
3. Spread and Rest Operator, Default Parameter
Spread (...
) - Expands elements
The spread operator allows expanding arrays or objects.
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5]; // [1, 2, 3, 4, 5]
Rest (...
) - Gathers arguments
It collects multiple arguments into an array.
function sum(...nums) {
return nums.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
Default Parameters
A function parameter with a default value when no argument is passed.
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // Hello, Guest
4. Deep Copy vs Shallow Copy
Shallow Copy
A shallow copy only copies object references, so modifying the copied object affects the original.
let obj1 = { name: "Alice", address: { city: "NY" } };
let obj2 = { ...obj1 };
obj2.address.city = "LA";
console.log(obj1.address.city); // "LA" (Modified)
Deep Copy
A deep copy creates a new object, preventing unintended modifications.
let obj3 = JSON.parse(JSON.stringify(obj1));
obj3.address.city = "Chicago";
console.log(obj1.address.city); // "LA" (Unchanged)
5. Promise, Callback, Async-Await
Callback
A function passed as an argument to another function.
function fetchData(callback) {
setTimeout(() => callback("Data received"), 2000);
}
fetchData(console.log); // Output: Data received
Promise
A promise is an object that represents a future value (pending, fulfilled, rejected).
let promise = new Promise((resolve) => setTimeout(() => resolve("Data received"), 2000));
promise.then(console.log);
Async/Await
It simplifies working with promises.
Makes function asynchronous.
async function fetchData() {
let data = await promise;
console.log(data);
}
fetchData();
6. Difference Between Promise and Callback
Feature | Callback | Promise |
---|---|---|
Readability | Nested (callback hell) | Cleaner with .then()
|
Error Handling | Hard to manage |
.catch() for errors |
Chaining | Difficult | Easy with .then()
|
7. What is Event Bubbling and Capturing?
Bubbling (Default)
Event Bubbling means events travel from the child to the parent.
document.getElementById("child").addEventListener("click", () => console.log("Child clicked"));
document.getElementById("parent").addEventListener("click", () => console.log("Parent clicked"));
Clicking child logs:
Child clicked
Parent clicked
Capturing
Event Capturing means events travel from the parent to the child.
document.getElementById("parent").addEventListener("click", () => console.log("Parent clicked"), true);
8. What is a Higher-Order Function?
A function that takes another function as an argument or returns a function.
function operate(fn, a, b) {
return fn(a, b);
}
console.log(operate((x, y) => x + y, 2, 3)); // 5
9. Different Types of Functions in JavaScript
- Named Functions
- Anonymous Functions
- Arrow Functions
- IIFE (Immediately Invoked Function Expression)
(function() {
console.log("IIFE runs automatically");
})();
10. What is an Arrow Function?
A shorter syntax for functions with lexical "this".
const add = (a, b) => a + b;
console.log(add(5, 3)); // 8
11. Call, Apply, Bind
They control "this" context.
let obj = { name: "Alice" };
function greet(age) { console.log(`${this.name} is ${age} years old`); }
greet.call(obj, 25); // Alice is 25
greet.apply(obj, [30]); // Alice is 30
let boundFunc = greet.bind(obj);
boundFunc(40); // Alice is 40
12. Ways to Create Object
1.Object Literal
2.Constructor Function
3.Object.create()
4.Class-based
let obj1 = {};
let obj2 = new Object();
let obj3 = Object.create(null);
13. What is Prototype Inheritance?
Allows objects to inherit properties from another object.
function Person(name) { this.name = name; }
Person.prototype.greet = function() { console.log(`Hello, ${this.name}`); };
let person = new Person("Alice");
person.greet(); // Hello, Alice
14. What is TypeScript?
TypeScript is a strongly typed superset of JavaScript.
15. Array & String Methods
// Array methods - map(), filter(), reduce(), push(), pop(), splice()
let arr = [1, 2, 3, 4];
arr.map(x => x * 2); // [2, 4, 6, 8]
// String methods - split(), toUpperCase(), trim(), substring()
"hello".toUpperCase(); // "HELLO"
16. Difference Between Java and JavaScript?
Feature | Java | JavaScript |
---|---|---|
Type | Statically Typed | Dynamically Typed |
Usage | Backend (JVM) | Frontend & Backend |
17. What is Throttling & Debouncing
Throttling: Limits function execution rate.
Debouncing: Executes only after a pause.
// Throttling
function throttle(fn, limit) {
let lastCall = 0;
return function () {
let now = Date.now();
if (now - lastCall >= limit) {
fn();
lastCall = now;
}
};
}
// Debouncing
function debounce(fn, delay) {
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(fn, delay);
};
}
18. Difference Between Null & Undefined
Feature | Null | Undefined |
---|---|---|
Type | Object | Undefined |
Value Assigned | Yes | No |
let a; // undefined
let b = null; // null
19. Falsy Values
false
0
""
null
undefined
NaN
20. Execution Context, Event Loop, Call Stack, Call Queue, and Microtask Queue
Understanding JavaScript’s execution model is crucial for writing efficient code. JavaScript is single-threaded, meaning it executes one task at a time, but it can handle asynchronous operations using the
Manages code execution using the call stack and task queue.
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
Output:
Start
End
Promise
Timeout
Event Loop.
1. Execution Context
An Execution Context is the environment in which JavaScript code is executed. It consists of:
- Global Execution Context (GEC) – Created when the JavaScript file runs.
- Function Execution Context (FEC) – Created when a function is invoked.
Example:
console.log("Start");
function greet() {
console.log("Hello");
}
greet(); // Function Execution Context created
console.log("End");
Execution Order:
- Global Execution Context (GEC) is created.
-
console.log("Start")
runs. - Function
greet()
is called → New Function Execution Context (FEC) is created. - Inside
greet()
,console.log("Hello")
runs. - Function context is destroyed, and control returns to the global context.
-
console.log("End")
runs.
2. Call Stack (Execution Stack)
The Call Stack is a data structure where function execution contexts are pushed when functions are called and popped when execution is complete.
Example:
function first() {
second();
console.log("First");
}
function second() {
console.log("Second");
}
first();
console.log("End");
Call Stack Execution:
-
first()
is called → Pushed onto the stack. -
second()
is called insidefirst()
→ Pushed onto the stack. -
console.log("Second")
executes →second()
is removed from the stack. -
console.log("First")
executes →first()
is removed. -
console.log("End")
executes.
📌 Key Point: JavaScript runs code synchronously in the call stack unless an asynchronous function is encountered.
3. Event Loop
The Event Loop ensures that JavaScript does not block execution while waiting for asynchronous operations (e.g., setTimeout
, Promises, API calls).
📌 Process of Event Loop:
- JavaScript executes synchronous code (Call Stack).
- When an asynchronous operation occurs (
setTimeout
,fetch
), it is sent to the Web APIs (handled outside the call stack). - When the operation completes, it moves to the Callback Queue or Microtask Queue (depending on the type).
- The Event Loop checks if the Call Stack is empty. If yes, it pushes the next task from the queue to the Call Stack for execution.
4. Callback Queue (Task Queue)
The Callback Queue holds callback functions from asynchronous tasks like setTimeout()
and DOM events.
Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
console.log("End");
Execution Order:
-
"Start"
logs immediately. -
setTimeout()
sends the callback to Web APIs. -
"End"
logs. -
Event Loop moves the
setTimeout
callback from the Callback Queue to the Call Stack when it's empty. -
"Timeout"
logs last.
📌 Even though setTimeout
has 0ms
, it doesn’t execute immediately because synchronous tasks are completed first.
5. Microtask Queue (Priority Queue)
The Microtask Queue has higher priority than the Callback Queue. It contains:
- Promises (
.then()
,.catch()
) - Mutation Observers
- process.nextTick() (Node.js only)
Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
Execution Order:
-
"Start"
logs. -
setTimeout
sends callback to Web API. -
Promise.resolve().then()
goes to the Microtask Queue. -
"End"
logs. - The Microtask Queue executes first →
"Promise"
logs. - Finally, Event Loop moves the
setTimeout
callback to the Call Stack →"Timeout"
logs.
📌 Key Takeaway:
- Microtasks run before normal callbacks.
- Promises execute before
setTimeout()
even if both are asynchronous.
6. Full Execution Flow Example
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise 1"))
.then(() => console.log("Promise 2"));
console.log("End");
Execution Order:
-
"Start"
logs. -
setTimeout()
moves to Web API. - Promise goes to the Microtask Queue.
-
"End"
logs. -
Microtask Queue executes first →
"Promise 1"
logs. -
"Promise 2"
logs (since.then()
is also a microtask). -
Event Loop picks
setTimeout
callback →"Timeout"
logs.
Final Output:
Start
End
Promise 1
Promise 2
Timeout
Conclusion
Concept | Description |
---|---|
Execution Context | Environment where JavaScript executes (GEC & FEC). |
Call Stack | Manages function execution. Last-in, first-out (LIFO). |
Event Loop | Moves tasks from queues to the Call Stack. |
Callback Queue | Stores callbacks (e.g., setTimeout ). Lower priority than Microtasks. |
Microtask Queue | Higher priority queue (Promises, MutationObserver ). |
🚀 Key Takeaways:
- The Call Stack executes synchronous code.
- The Event Loop moves asynchronous tasks from Queues to the Call Stack.
- The Microtask Queue (
Promises
) has higher priority than the Callback Queue (setTimeout
).
21. JSON Methods
let obj = { name: "Alice" };
let str = JSON.stringify(obj); // Convert object to string
let parsed = JSON.parse(str); // Convert string to object
22. What is Closure?
A function with access to its parent scope, and makes stateful function. Helps to implement Encapsulation and helps to expose only what we want to.
function outer() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
let counter = outer();
counter(); // 1
counter(); // 2
23. What is setTimeout
and setInterval
in JavaScript?
One-time vs Repeated execution.
setTimeout
- Executes a function after a specified time.
setTimeout(() => console.log("Hello after 2 seconds"), 2000);
setInterval
- Executes a function repeatedly at specified intervals.
let count = 0;
let interval = setInterval(() => {
console.log(`Count: ${++count}`);
if (count === 5) clearInterval(interval);
}, 1000);
24. What is Object.seal
and Object.freeze
in JavaScript?
Sealed prevents adding/deleting properties.
Frozen prevents modifications.
Feature | Object.seal() |
Object.freeze() |
---|---|---|
Prevents new properties? | ✅ Yes | ✅ Yes |
Prevents deletion? | ✅ Yes | ✅ Yes |
Prevents modification of existing properties? | ❌ No | ✅ Yes |
const obj = { name: "Alice" };
Object.seal(obj);
obj.name = "Bob"; // Allowed
delete obj.name; // Not allowed
Object.freeze(obj);
obj.name = "Charlie"; // Not allowed
25. Difference Between Map
and Set
in JavaScript?
- Map: A key-value pair collection where keys can be of any type.
- Set: A collection of unique values.
Feature | Map |
Set |
---|---|---|
Stores Key-Value Pairs? | ✅ Yes | ❌ No |
Allows Duplicate Values? | ❌ No | ❌ No |
Order is Maintained? | ✅ Yes | ✅ Yes |
let map = new Map();
map.set("name", "Alice");
let set = new Set([1, 2, 3, 3]);
console.log(set); // {1, 2, 3} (duplicates removed)
26. What is WeakMap
and WeakSet
?
- WeakMap only stores objects as keys and doesn't prevent garbage collection. Stores key-value pairs where keys are objects and are weakly referenced.
- WeakSet only stores objects, ensuring efficient memory management. A collection of objects with weak references.
let weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, "Data");
let weakSet = new WeakSet();
weakSet.add(obj);
27. What is sessionStorage
, localStorage
, and cookie
?
Storage | Expiry | Max Size | Accessible by JS? |
---|---|---|---|
localStorage |
Never expires | ~5MB | ✅ Yes |
sessionStorage |
Expires on page close | ~5MB | ✅ Yes |
Cookies | Set manually | ~4KB | ✅ Yes |
localStorage.setItem("user", "Alice");
sessionStorage.setItem("session", "active");
document.cookie = "token=12345; expires=Fri, 31 Dec 2025 12:00:00 UTC";
28. Write a Program to Sort an Array
let arr = [5, 2, 9, 1, 5, 6];
arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 5, 5, 6, 9]
29. What is map
, filter
, and reduce
in JavaScript?
-
map()
- Transforms each element. creates a new array by applying a function to each element. -
filter()
- Filters based on condition. creates a new array with elements that pass a condition. -
reduce()
- Reduces array to single value. applies a function to accumulate values.
let nums = [1, 2, 3, 4];
let doubled = nums.map(x => x * 2); // [2, 4, 6, 8]
let evens = nums.filter(x => x % 2 === 0); // [2, 4]
let sum = nums.reduce((acc, num) => acc + num, 0); // 10
console.log(doubled); // [2, 4, 6, 8]
console.log(evens); // [2, 4]
console.log(sum); // 10
30. What is a Generator Function in JavaScript?
A function that can pause and resume execution using yield
.
function* gen() {
yield 1;
yield 2;
yield 3;
}
let iterator = gen();
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
31. How to Stop Event Propagation in JavaScript?
Use event.stopPropagation() to prevent bubbling or capturing.
document.getElementById("child").addEventListener("click", (e) => {
e.stopPropagation();
console.log("Child Clicked");
});
32. What is Hoisting in JavaScript?
Hoisting moves variable and function declarations to the top of their scope but not initialization.
console.log(x); // undefined (not an error)
var x = 5;
foo(); // Works because function is hoisted
function foo() {
console.log("Hoisted function");
}
33. What is the Temporal Dead Zone in JavaScript?
The time between variable declaration (let/const) and initialization.
console.log(a); // ReferenceError
let a = 5;
34. What is Function Currying?
Transforming a function to take multiple parameters one at a time. Breaking down a function into smaller functions that take one argument at a time.
function curry(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
console.log(curry(1)(2)(3)); // 6
35. What is Mutation Observer in JavaScript?
It watches for changes in the DOM. It detects changes in the DOM.
let observer = new MutationObserver(() => console.log("DOM changed"));
observer.observe(document.body, { childList: true });
document.body.appendChild(document.createElement("div"));
36. What is Memoization in JavaScript?
Storing function results to avoid redundant computations. Caching results to improve performance.
function memoize(fn) {
let cache = {};
return function (num) {
if (num in cache) return cache[num];
else return (cache[num] = fn(num));
};
}
const factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));
console.log(factorial(5)); // 120
Top comments (0)