Top 50 JavaScript Interview Questions and Answers (2025 Edition)
Top 50 JavaScript Interview Questions and Answers (2025)
Looking to ace your JavaScript interview? Whether you’re a college student, fresher, job seeker, or experienced developer, this guide is packed with the top 50 most frequently asked JavaScript interview questions with clear, human-like explanations and real-time examples. Letβs dive in! π
Q1. What is JavaScript and how is it different from Java?
Answer:
JavaScript is a lightweight, interpreted programming language primarily used to add interactivity and dynamic content to websites. It runs on the browser (client-side) and is a core technology of the web along with HTML and CSS.
Difference from Java:
JavaScript | Java |
---|---|
Interpreted | Compiled |
Used for frontend web development | Used for backend/server-side and applications |
Runs in browser | Runs on JVM |
Loosely typed | Strongly typed |
Example:
Q2. What are the different data types in JavaScript?
Answer:
JavaScript supports the following primitive and reference data types:
-
Primitive Types:
-
String
-
Number
-
Boolean
-
Undefined
-
Null
-
BigInt
-
Symbol
-
-
Reference Types:
-
Objects
-
Arrays
-
Functions
-
Example:
Q3. What is the difference between var
, let
, and const
?
Answer:
Keyword | Scope | Reassignable | Hoisted |
---|---|---|---|
var |
Function | Yes | Yes (undefined) |
let |
Block | Yes | No |
const |
Block | No | No |
Example:
1 2 3 |
var x = 5; let y = 10; const z = 15; |
Use let
and const
in modern JavaScript for better scoping and safety.
Q4. What are arrow functions in JavaScript?
Answer:
Arrow functions are a shorter syntax for writing functions introduced in ES6, and they donβt bind their own this
.
Syntax:
Short version (for single return):
Q5. What is the difference between ==
and ===
in JavaScript?
Answer:
-
==
(Loose Equality): Compares values after type coercion -
===
(Strict Equality): Compares values and types
Example:
Always prefer ===
to avoid unexpected type conversions.
Q6. Explain event delegation in JavaScript.
Answer:
Event Delegation is a technique where a single event listener is added to a parent element to handle events for all of its child elements, using event bubbling.
Why use it?
-
Better performance
-
Fewer event listeners
Example:
1 2 3 4 5 |
document.getElementById("list").addEventListener("click", function(e) { if (e.target.tagName === "LI") { alert("Item clicked: " + e.target.innerText); } }); |
Q7. What is the difference between null
and undefined
?
Answer:
Value | Meaning |
---|---|
undefined |
A variable is declared but not assigned a value |
null |
A deliberate assignment of “no value” |
Example:
1 2 3 4 5 |
let a; console.log(a); // undefined let b = null; console.log(b); // null |
Q8. What are closures in JavaScript?
Answer:
A closure is when a function “remembers” the variables from its outer lexical scope even after that outer function has finished executing.
Example:
1 2 3 4 5 6 7 8 9 10 11 |
function outer() { let counter = 0; return function inner() { counter++; return counter; }; } const count = outer(); console.log(count()); // 1 console.log(count()); // 2 |
Closures are used in data privacy and callback functions.
Q9. What is hoisting in JavaScript?
Answer:
Hoisting is JavaScript’s default behavior of moving declarations (not initializations) to the top of the current scope.
Example:
1 2 |
console.log(x); // undefined var x = 10; |
Functions are fully hoisted, but variables declared with let
and const
are not initialized during hoisting.
Q10. Explain the difference between synchronous and asynchronous JavaScript.
Answer:
Type | Description |
---|---|
Synchronous | Code is executed line by line, blocking the next line until current finishes |
Asynchronous | Code execution doesn’t wait; useful for tasks like API calls, timers, etc. |
Example using setTimeout
:
1 2 3 4 5 6 7 |
console.log("Start"); setTimeout(() => { console.log("Async Code"); }, 1000); console.log("End"); |
Output:
1 2 3 |
Start End Async Code |
Q11. What is the DOM in JavaScript?
Answer:
The DOM (Document Object Model) is a tree-like structure representing the contents of a web page. JavaScript uses the DOM to access and manipulate HTML and CSS dynamically.
Example:
DOM allows developers to:
-
Change content
-
Modify styles
-
Add/remove elements
-
Respond to events
Q12. What is the difference between call()
, apply()
, and bind()
?
Answer:
Method | Description | Example |
---|---|---|
call() |
Invokes function immediately with arguments passed individually | fn.call(obj, arg1, arg2) |
apply() |
Invokes function with arguments passed as an array | fn.apply(obj, [arg1, arg2]) |
bind() |
Returns a new function with a bound context (does not invoke immediately) | const newFn = fn.bind(obj) |
Example:
1 2 3 4 5 6 7 8 9 |
function greet(age) { console.log(`${this.name} is ${age} years old`); } const person = { name: "Brahmi" }; greet.call(person, 25); // Brahmi is 25 years old greet.apply(person, [30]); // Brahmi is 30 years old const boundGreet = greet.bind(person); boundGreet(35); // Brahmi is 35 years old |
Q13. What is an IIFE (Immediately Invoked Function Expression)?
Answer:
An IIFE is a function that runs immediately after being defined. It’s often used to create a private scope.
Syntax:
1 2 3 |
(function() { console.log("This runs instantly!"); })(); |
Useful for:
-
Avoiding polluting the global scope
-
Creating modular and self-contained code
Q14. What are template literals in JavaScript?
Answer:
Template literals (introduced in ES6) allow multi-line strings and embedded expressions using backticks ().
Example:
1 2 3 4 |
let name = "John"; let greeting = `Hello, ${name}! Welcome to JavaScript world.`; console.log(greeting); |
They simplify string concatenation and enhance readability.
Q15. What is the difference between for...of
and for...in
loops?
Answer:
Loop | Iterates Over | Use Case |
---|---|---|
for...in |
Keys (property names) of an object | Objects |
for...of |
Values of an iterable (like arrays) | Arrays, strings, etc. |
Example:
1 2 3 4 5 6 7 8 9 |
let arr = ['a', 'b', 'c']; for (let i in arr) { console.log(i); // Index: 0, 1, 2 } for (let val of arr) { console.log(val); // Values: a, b, c } |
Q16. What are promises in JavaScript?
Answer:
A promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
States:
-
Pending
-
Fulfilled
-
Rejected
Example:
1 2 3 4 5 |
let myPromise = new Promise((resolve, reject) => { setTimeout(() => resolve("Success!"), 1000); }); myPromise.then(result => console.log(result)); // Success! |
Promises help write cleaner async code without deeply nested callbacks.
Q17. What is async/await in JavaScript?
Answer:async/await
is syntactic sugar over promises that allows writing asynchronous code as if it were synchronous.
Example:
1 2 3 4 5 6 |
async function fetchData() { let response = await fetch("https://api.example.com/data"); let data = await response.json(); console.log(data); } fetchData(); |
β
Cleaner, more readable than .then()
chains.
Q18. What is a callback function?
Answer:
A callback function is a function passed as an argument to another function and executed later.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function greetUser(name, callback) { console.log("Hi " + name); callback(); } function sayBye() { console.log("Bye!"); } greetUser("Emma", sayBye); // Output: // Hi Emma // Bye! |
Used heavily in asynchronous programming (e.g., event handling, timers).
Q19. What is the difference between mutable and immutable data types in JavaScript?
Answer:
Type | Can be Changed? | Examples |
---|---|---|
Mutable | Yes | Arrays, Objects |
Immutable | No | Strings, Numbers, Booleans |
Example:
1 2 3 4 5 |
let arr = [1, 2]; arr.push(3); // Modified β mutable let str = "hello"; str[0] = "H"; // No change β immutable |
Understanding this helps avoid bugs related to unintended data mutations.
Q20. How is memory managed in JavaScript?
Answer:
JavaScript uses automatic garbage collection to manage memory. It tracks which values are accessible and frees memory used by unreferenced values.
Key Concepts:
-
Reachability: If a value is reachable, it’s kept in memory.
-
Garbage Collection: Unreachable objects are removed.
Example:
1 2 |
let obj = { name: "Bob" }; obj = null; // Original object becomes unreachable |
π‘ Tip: Avoid memory leaks by:
-
Removing unused event listeners
-
Clearing intervals/timers
-
Nullifying unnecessary object references
Q21. What is event delegation in JavaScript?
Answer:
Event delegation is a technique where a parent element handles events of its child elements. Instead of attaching event listeners to every child, you attach one to the parent and use event.target
to detect which child triggered the event.
Benefits:
-
Better performance
-
Less memory usage
-
Easier to handle dynamically added elements
Example:
1 2 3 4 5 |
document.getElementById("list").addEventListener("click", function(event) { if (event.target.tagName === "LI") { console.log("You clicked:", event.target.textContent); } }); |
Q22. What is the difference between ==
and ===
in JavaScript?
Answer:
Operator | Description | Example |
---|---|---|
== |
Loose equality (performs type coercion) | 5 == "5" β true |
=== |
Strict equality (no type coercion) | 5 === "5" β false |
Best Practice:
Always use ===
for strict and predictable comparisons.
Q23. What are arrow functions in JavaScript?
Answer:
Arrow functions (=>
) are a shorter syntax for writing functions, introduced in ES6.
Syntax:
1 |
const add = (a, b) => a + b; |
Key differences from regular functions:
-
No own
this
binding -
Not suitable for methods or constructors
-
Cannot use
arguments
object
Example:
1 2 |
let greet = name => console.log(`Hello, ${name}`); greet("Alex"); |
Q24. What is a closure in JavaScript?
Answer:
A closure is created when a function remembers its lexical scope even when the function is executed outside that scope.
Use cases:
-
Data privacy
-
Function factories
-
Callback-based logic
Example:
1 2 3 4 5 6 7 8 9 10 |
function outer() { let counter = 0; return function inner() { counter++; return counter; }; } const increment = outer(); console.log(increment()); // 1 console.log(increment()); // 2 |
Also Read,
Top 50 HTML Interview Questions and Answers |
Q25. What is hoisting in JavaScript?
Answer:
Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope before code execution.
-
Variables (
var
) and function declarations are hoisted. -
let
andconst
are hoisted but not initialized (TDZ – Temporal Dead Zone).
Example:
1 2 |
console.log(a); // undefined (due to hoisting) var a = 5; |
Note: Prefer let
and const
to avoid hoisting issues.
Q26. What are higher-order functions in JavaScript?
Answer:
A higher-order function is a function that takes another function as an argument, returns a function, or both.
Example:
1 2 3 4 5 6 7 |
function greet(name) { return function(message) { console.log(`Hi ${name}, ${message}`); }; } const greetJohn = greet("John"); greetJohn("Good morning!"); |
Examples in JavaScript:
-
map()
-
filter()
-
reduce()
Q27. What is the event loop in JavaScript?
Answer:
The event loop is the mechanism that handles asynchronous operations like setTimeout
, Promises, and I/O in a non-blocking way.
Flow:
-
Executes the call stack
-
Checks the message queue
-
Moves callbacks to the call stack when it’s empty
Example:
1 2 3 4 5 6 7 8 |
console.log("Start"); setTimeout(() => console.log("Timeout"), 0); console.log("End"); // Output: // Start // End // Timeout |
Q28. What is the difference between null
and undefined
?
Answer:
Term | Meaning |
---|---|
undefined |
A variable that has been declared but not assigned a value |
null |
Represents the intentional absence of any object value |
Example:
1 2 3 4 5 |
let a; console.log(a); // undefined let b = null; console.log(b); // null |
Q29. What are JavaScript data types?
Answer:
JavaScript has 8 data types:
Primitive types:
-
String
-
Number
-
Boolean
-
Null
-
Undefined
-
Symbol (ES6)
-
BigInt (ES11)
Non-primitive:
8. Object (includes arrays, functions, dates, etc.)
Example:
1 2 3 4 5 |
let name = "Alice"; // String let age = 25; // Number let active = true; // Boolean let data = null; // Null let info; // Undefined |
Q30. What is the difference between synchronous and asynchronous code in JavaScript?
Answer:
Type | Description |
---|---|
Synchronous | Executes line by line, blocking the thread |
Asynchronous | Executes in the background, non-blocking |
Synchronous Example:
Asynchronous Example:
Asynchronous code improves performance and responsiveness.
Q31. What are JavaScript Generators and how are they different from regular functions?
Answer:
Generators are special functions in JavaScript that can pause and resume execution using the function*
syntax and yield
keyword.
Key Differences:
-
Use
function*
to define -
Use
yield
to pause execution -
Return an iterator object
Example:
1 2 3 4 5 6 7 8 9 |
function* counter() { yield 1; yield 2; yield 3; } const gen = counter(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } |
Generators are ideal for lazy evaluations, handling asynchronous flows, and implementing iterators.
Q32. What is the event loop in JavaScript?
Answer:
The event loop is the core of JavaScript’s non-blocking concurrency model, allowing async operations like callbacks, promises, and DOM events.
Working Process:
-
Executes the call stack (main thread)
-
When async code is encountered (e.g.,
setTimeout
,fetch
), it’s sent to the Web APIs -
After completion, the callback is pushed to the task queue
-
The event loop checks if the call stack is empty, then pushes queued tasks to it
Example:
1 2 3 4 5 |
console.log("Start"); setTimeout(() => console.log("Timeout"), 0); console.log("End"); // Output: Start β End β Timeout |
Q33. What are WeakMap and WeakSet in JavaScript?
Answer:
-
WeakMap
: A collection of key-value pairs where keys must be objects -
WeakSet
: A collection of objects only, without duplicates
Advantages:
-
Keys are weakly held, meaning they are eligible for garbage collection
-
Used to prevent memory leaks
Example:
They donβt support iteration and donβt prevent memory cleanup.
Q34. Explain the concept of reflow and repaint in the browser rendering process.
Answer:
When DOM changes happen, the browser may trigger:
-
Repaint: Changes only appearance (e.g., color, visibility)
-
Reflow (Layout): Changes that affect layout or position, like element size or DOM structure
Reflow is more expensive than repaint.
Minimizing DOM manipulations and batching changes improves performance.
Tip: Use classList.add()
instead of directly changing multiple styles.
Q35. What are the different types of memory in JavaScript?
Answer:
JavaScript uses:
-
Stack Memory
-
Stores primitive values and function execution context
-
Fast access
-
-
Heap Memory
-
Stores objects, arrays, and functions
-
Dynamically allocated and larger
-
Example:
1 2 |
let num = 5; // Stack let obj = { age: 25 }; // Heap |
Understanding memory helps debug leaks and optimize performance.
Q36. What are Service Workers in JavaScript?
Answer:
A Service Worker is a background script that runs independently of the web page, enabling:
-
Offline experiences
-
Background sync
-
Push notifications
-
Caching resources
Key Features:
-
Runs in a separate thread
-
Cannot access the DOM directly
-
Acts like a proxy between the app and the network
Basic Registration:
1 2 3 |
if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/sw.js"); } |
Q37. How does optional chaining work in JavaScript (?.
)?
Answer:
Optional chaining (?.
) allows you to safely access deeply nested properties without checking each level.
Example:
Helps prevent runtime errors from accessing undefined
or null
properties.
Q38. What is the difference between microtasks and macrotasks in JavaScript?
Answer:
Type | Examples | Priority |
---|---|---|
Microtasks | Promise.then() , queueMicrotask() |
High priority (executed after current task) |
Macrotasks | setTimeout , setInterval , DOM events |
Lower than microtasks |
Execution Order:
1 2 3 4 5 6 7 8 |
console.log("Start"); setTimeout(() => console.log("Macrotask"), 0); Promise.resolve().then(() => console.log("Microtask")); console.log("End"); // Output: Start β End β Microtask β Macrotask |
Q39. What is function memoization and how do you implement it in JavaScript?
Answer:
Memoization is an optimization technique to cache previously computed results of function calls.
Use case: Improve performance of recursive or heavy computations.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function memoize(fn) { const cache = {}; return function (n) { if (cache[n]) return cache[n]; return (cache[n] = fn(n)); }; } const factorial = memoize(function (x) { if (x <= 1) return 1; return x * factorial(x - 1); }); console.log(factorial(5)); // 120 |
Q40. What is the Temporal API in JavaScript?
Answer:
The Temporal API is a new date and time handling API (introduced to replace Date
) with better precision, immutability, and time zone support.
Key Features:
-
Precise time calculations
-
Time zones support
-
Immutable objects
-
Safer than
Date
Example:
1 2 3 4 5 |
const now = Temporal.Now.instant(); console.log(now.toString()); // 2025-05-29T... const date = Temporal.PlainDate.from("2025-12-25"); console.log(date.add({ days: 5 }).toString()); // 2025-12-30 |
Note: Still in proposal stage in some environmentsβcheck browser compatibility.
Q41. What is the difference between Object.freeze()
and const
in JavaScript?
Answer:
Both are used for immutability, but they serve different purposes:
-
const
prevents reassignment of a variable. -
Object.freeze()
makes an object immutable, i.e., its properties cannot be changed, added, or deleted.
Example:
1 2 3 4 5 |
const obj = { name: "Alex" }; obj.name = "Sam"; // valid Object.freeze(obj); obj.name = "Bob"; // no effect in strict mode |
Object.freeze()
is shallowβnested objects are still mutable unless also frozen.
Q42. What is tail call optimization in JavaScript?
Answer:
Tail Call Optimization (TCO) is a technique where the last action of a function is a call to another function, allowing the JS engine to reuse stack frames, preventing stack overflow.
Example (with tail call):
1 2 3 4 |
function factorial(n, acc = 1) { if (n === 0) return acc; return factorial(n - 1, acc * n); } |
β οΈ Supported in strict mode in some engines (e.g., Safari).
Q43. What is the difference between ==
and Object.is()
in JavaScript?
Answer:
Comparison | Behavior |
---|---|
== |
Performs type coercion |
Object.is() |
No coercion, uses SameValue algorithm |
Special Case:
1 2 3 4 5 |
NaN === NaN // false Object.is(NaN, NaN) // true +0 === -0 // true Object.is(+0, -0) // false |
Use Object.is()
when you want exact identity checks.
Q44. What is the difference between call
, apply
, and bind
methods?
Answer:
Method | Description | Example |
---|---|---|
call() |
Calls function with this and individual arguments |
fn.call(thisArg, arg1, arg2) |
apply() |
Calls function with this and array of arguments |
fn.apply(thisArg, [args]) |
bind() |
Returns a new function with this bound |
let newFn = fn.bind(thisArg) |
Example:
1 2 3 4 5 6 7 8 9 |
function greet(msg) { return `${msg}, ${this.name}`; } const user = { name: "Ravi" }; console.log(greet.call(user, "Hello")); // Hello, Ravi console.log(greet.apply(user, ["Hi"])); // Hi, Ravi const greetRavi = greet.bind(user); console.log(greetRavi("Welcome")); // Welcome, Ravi |
Q45. How can you deep clone an object in JavaScript?
Answer:
Deep cloning means copying all nested objects and arrays.
Common Methods:
-
StructuredClone (modern)
1 |
const newObj = structuredClone(original); |
-
JSON method (basic)
1 |
const newObj = JSON.parse(JSON.stringify(original)); |
β οΈ Doesnβt handle undefined
, functions, or circular references.
-
Manual recursion or libraries (e.g., Lodash’s
cloneDeep
) for complex cases.
Q46. What is the Temporal Dead Zone (TDZ) in JavaScript?
Answer:
The TDZ is the time between the declaration of a variable with let
/const
and its initialization, during which accessing it results in a ReferenceError.
Example:
1 2 |
console.log(a); // ReferenceError let a = 10; |
Variables declared with var
do not have TDZ, which can lead to undefined
.
Q47. What is the difference between .forEach()
, .map()
, .filter()
, and .reduce()
?
Answer:
Method | Purpose | Returns |
---|---|---|
.forEach() |
Iterates for side effects | undefined |
.map() |
Transforms array | New array |
.filter() |
Filters items | New array |
.reduce() |
Reduces to a value | Single value |
Example:
1 2 3 4 5 6 |
const nums = [1, 2, 3]; nums.forEach(n => console.log(n)); // 1 2 3 console.log(nums.map(n => n * 2)); // [2, 4, 6] console.log(nums.filter(n => n > 1)); // [2, 3] console.log(nums.reduce((a, b) => a + b));// 6 |
Q48. What is a throttling function and how is it different from debouncing?
Answer:
Concept | Description | Use Case |
---|---|---|
Debounce | Executes after delay of inactivity | Search input |
Throttle | Executes at fixed intervals | Scroll event |
Throttle Example:
1 2 3 4 5 6 7 8 9 10 |
function throttle(func, limit) { let inThrottle; return function() { if (!inThrottle) { func(); inThrottle = true; setTimeout(() => (inThrottle = false), limit); } }; } |
Q49. What is the use of Symbol
in JavaScript?
Answer:Symbol
is a primitive data type introduced in ES6 for creating unique identifiers, often used for object keys to avoid naming collisions.
Example:
Symbols are not enumerable and provide encapsulation.
Q50. What is the difference between synchronous and asynchronous code in JavaScript?
Answer:
Type | Behavior | Example |
---|---|---|
Synchronous | Runs in blocking order | for , if , DOM |
Asynchronous | Non-blocking, waits for callbacks | setTimeout , fetch , Promise |
Async Example:
1 2 3 4 5 |
console.log("1"); setTimeout(() => console.log("2"), 0); console.log("3"); // Output: 1, 3, 2 |
Async programming enables better performance and responsiveness in apps.
π Conclusion
Mastering these top 50 JavaScript interview questions can significantly boost your confidence and chances of success. Whether you’re a student, fresher, or experienced developer, understanding these concepts with real examples will help you tackle any interview with ease. Keep practicing, stay curious, and you’ll crack your dream job in no time!
π€ Stay Updated with NextGen Careers Hub
π± Follow us onΒ Instagram
πΊ Subscribe to us onΒ YouTube
Please share our website with others:Β NextGenCareersHub.in
Comments are closed.