JavaScript remains one of the most versatile and in-demand programming languages in 2026. Whether you are a fresher or a professional developer, mastering JavaScript is crucial for career advancement.
Interviews for JavaScript roles often cover a wide range of questions, from basic concepts to advanced problem-solving.
This guide covers 100+ JavaScript interview questions and answers for 2026, starting with fundamentals and progressing to advanced concepts, browser behaviour and coding-based interview problems.
JavaScript Interview Questions for Freshers
1. What is JavaScript?
JavaScript is a high-level, dynamically typed programming language used to add behaviour and interactivity to applications. It runs natively in web browsers and can also run outside the browser through runtimes such as Node.js.
JavaScript supports multiple programming styles, including procedural, functional and object-oriented programming through prototypes and classes.
2. Is JavaScript compiled or interpreted?
Modern JavaScript is not accurately described as purely interpreted. JavaScript engines parse the source code and may use Just-In-Time (JIT) compilation and runtime optimisation to execute frequently used code efficiently.
For example, engines such as V8 can optimise code while the program is running instead of compiling the entire application ahead of time in the same way as a traditional ahead-of-time compiled language.
3. Is JavaScript statically typed or dynamically typed?
JavaScript is dynamically typed. A variable is not permanently restricted to one data type and can hold values of different types at different points in the program.
let value = 10;
value = "hello";
value = true;The type belongs to the value rather than being fixed to the variable declaration.
4. What are the primitive data types in JavaScript?
JavaScript has seven primitive data types:
- String
- Number
- BigInt
- Boolean
- Undefined
- Null
- Symbol
Objects are non-primitive values. Arrays and functions are specialised forms of objects in JavaScript.
5. What is the difference between primitive and reference values?
Primitive values such as strings, numbers and booleans are immutable values. Objects, arrays and functions are objects, and variables referring to them hold references to those objects.
const a = ;
const b = a;
b.value = 2;
console.log(a.value); // 2Both a and b refer to the same object, so changing it through one reference is visible through the other.
6. What is the difference between var, let and const?
| Keyword | Scope | Redeclaration | Reassignment |
|---|---|---|---|
var | Function-scoped | Allowed in the same scope | Allowed |
let | Block-scoped | Not allowed in the same scope | Allowed |
const | Block-scoped | Not allowed in the same scope | Not allowed |
A const object can still have its properties changed. const prevents reassignment of the variable binding; it does not automatically make the referenced object immutable.
const user = ;
user.name = "Riya"; // allowed
// user = ; // TypeError7. What is the difference between == and === in JavaScript?
== performs loose equality and may convert operand types before comparison. === performs strict equality without type coercion.
5 == "5" // true
5 === "5" // falseStrict equality is generally easier to reason about because it avoids implicit type conversion.
8. What is type coercion in JavaScript?
Type coercion is the conversion of a value from one type to another. JavaScript can perform coercion implicitly, or developers can convert values explicitly.
"5" + 2 // "52"
"5" - 2 // 3
Number("5") // 5
String(10) // "10"The first two examples show implicit coercion. Number() and String() perform explicit conversion.
9. What is NaN in JavaScript?
NaN means Not-a-Number. It represents a numeric result that cannot be represented as a valid number.
Number("hello"); // NaNA useful interview detail is that:
typeof NaN; // "number"To check for NaN reliably, Number.isNaN() is usually preferable to comparing directly with NaN.
10. What is the difference between null and undefined?
undefined commonly means that a value has not been assigned or does not exist. null is an explicit value typically used to represent the intentional absence of a value.
let result;
console.log(result); // undefined
const selectedUser = null;One historical JavaScript quirk is:
typeof null; // "object"Despite that result, null is a primitive value, not an object.
11. What is hoisting in JavaScript?
Hoisting describes how JavaScript processes declarations before executing the code in a scope. It does not literally move source-code lines to the top.
Function declarations can normally be called before their textual declaration:
greet();
function greet() Variables declared with var exist before their declaration is reached but initially contain undefined. Variables declared with let and const also belong to their scope before the declaration line, but cannot be accessed during the Temporal Dead Zone.
12. What is the Temporal Dead Zone?
The Temporal Dead Zone (TDZ) is the period between entering a scope and reaching the declaration of a let, const or class binding. Accessing the binding during this period throws a ReferenceError.
13. What is scope in JavaScript?
Scope determines where a variable or function can be accessed.
- Global scope: accessible broadly within the relevant environment.
- Function scope: variables declared with
varinside a function belong to that function. - Block scope:
letandconstare scoped to blocks such as loops andifstatements. - Module scope: top-level declarations in an ES module belong to that module rather than becoming ordinary global bindings.
14. What is lexical scope?
Lexical scope means the accessibility of variables is determined by where functions and blocks are written in the source code.
const outer = "outside";
function showValue()
showValue(); // outsideThe function can access outer because it was defined within a scope where that binding is available.
15. What is a closure in JavaScript?
A closure is created when a function retains access to variables from its surrounding lexical environment even after the outer function has finished executing.
function createCounter() ;
}
const counter = createCounter();
counter(); // 1
counter(); // 2Closures are commonly used for encapsulating state, factory functions, event handlers and callbacks.
16. What is an IIFE in JavaScript?
An Immediately Invoked Function Expression (IIFE) is a function expression that executes as soon as it is created.
(function () )();IIFEs were historically useful for creating isolated scopes before ES modules and block-scoped declarations became widely used.
17. What are functions in JavaScript?
Functions are callable objects that encapsulate reusable behaviour. JavaScript supports several common function forms, including:
- function declarations;
- function expressions;
- arrow functions;
- methods;
- generator functions; and
- async functions.
Functions are first-class values, meaning they can be assigned to variables, stored in objects, passed to other functions and returned from functions.
18. What is a higher-order function?
A higher-order function accepts one or more functions as arguments, returns a function, or both.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(
number => number * 2
);
console.log(doubled); // [2, 4, 6, 8]Methods such as map(), filter() and reduce() are common examples of APIs that accept callback functions.
19. What is a callback function?
A callback is a function passed to another function so that it can be called at an appropriate point.
function processUser(name, callback)
processUser("Aman", user => `);
});Callbacks are used in synchronous APIs such as array methods and in asynchronous APIs such as event handlers.
20. What are arrow functions, and how are they different from regular functions?
Arrow functions provide a shorter syntax for function expressions.
const add = (a, b) => a + b;The major interview difference is that an arrow function does not create its own this, arguments or super binding. It uses this from the surrounding lexical context.
Arrow functions also cannot be used as constructors with new and are often unsuitable when a method specifically needs a dynamic this value.
Read Also: 50+ Java Interview Questions and Answers for 2-3 Years Experience
JavaScript Objects, Prototypes and Arrays Interview Questions
21. What is an object in JavaScript?
An object is a collection of properties where each property has a key and a value. Property values can be primitives, other objects or functions.
const user = `;
}
};Objects are commonly used to represent structured data and behaviour together.
22. What are the different ways to create objects in JavaScript?
Common approaches include:
- Object literal:
- Constructor function: used with
new - Object.create(): creates an object with a specified prototype
- Class syntax: provides a cleaner syntax over JavaScript’s prototype-based object model
const obj1 = ;
const obj2 = Object.create(null);
class User
}
const obj3 = new User("Aman");23. What is a prototype in JavaScript?
Every ordinary JavaScript object has an internal link to another object called its prototype, unless its prototype is explicitly set to null.
If JavaScript cannot find a requested property directly on an object, it searches the object’s prototype and then continues upward through the prototype chain.
24. What is prototype chaining?
Prototype chaining is the process JavaScript uses to look up properties through an object’s chain of prototypes.
const animal = ;
const dog = Object.create(animal);
dog.barks = true;
console.log(dog.barks); // true
console.log(dog.eats); // truebarks is found directly on dog, while eats is inherited from animal.
25. What is the difference between __proto__ and prototype?
prototype is a property found on constructor functions and is used for objects created with new.
__proto__ is a legacy accessor that exposes an object’s internal prototype link. In modern code, methods such as Object.getPrototypeOf() and Object.setPrototypeOf() are clearer alternatives.
function Person()
const person = new Person();
console.log(
Object.getPrototypeOf(person) === Person.prototype
); // true26. How does inheritance work in JavaScript?
JavaScript uses prototype-based inheritance. Objects can inherit properties and methods through their prototype chain.
Class syntax provides a more familiar way to express this relationship, but JavaScript classes still use prototypes internally.
class Animal
}
class Dog extends Animal
}
const dog = new Dog();
dog.speak(); // "sound"
dog.bark(); // "woof"27. What does the new keyword do in JavaScript?
When a constructor function is called with new, JavaScript roughly performs these steps:
- Creates a new object.
- Links the new object’s prototype to the constructor’s
prototypeproperty. - Calls the constructor with
thisreferring to the new object. - Returns the new object unless the constructor explicitly returns another object.
function Person(name)
const person = new Person("Aman");28. What is the this keyword in JavaScript?
The value of this depends mainly on how a function is called, not where the function is written.
Common cases include:
- Method call:
thisusually refers to the object before the dot. - Constructor call with new:
thisrefers to the new instance. - call(), apply() or bind():
thiscan be explicitly controlled. - Arrow function: it does not create its own
this; it uses the surrounding lexical value.
const user =
};
user.showName(); // Aman29. What is the difference between call(), apply() and bind()?
| Method | Behaviour |
|---|---|
call() | Invokes the function immediately and passes arguments separately |
apply() | Invokes the function immediately and accepts arguments as an array or array-like object |
bind() | Returns a new function with a specified this value and optional preset arguments |
function greet(greeting) , $ `;
}
const user = ;
greet.call(user, "Hello");
greet.apply(user, ["Hi"]);
const boundGreet = greet.bind(user);
boundGreet("Welcome");30. What is a factory function?
A factory function is a regular function that creates and returns an object without requiring the new keyword.
function createUser(name) `;
}
};
}
const user = createUser("Aman");31. What is a constructor function?
A constructor function is a regular function intended to create object instances with the new keyword.
function Person(name)
Person.prototype.greet = function () `;
};
const person = new Person("Aman");Constructor functions were widely used before class syntax was introduced and remain important for understanding prototypes.
32. What is the difference between Object.freeze() and Object.seal()?
| Object.freeze() | Object.seal() |
|---|---|
| Prevents adding properties | Prevents adding properties |
| Prevents deleting properties | Prevents deleting properties |
| Prevents changing existing data properties | Allows changing writable existing properties |
| Is shallow | Is shallow |
A frozen object is not automatically deeply immutable. Nested objects can still be modified unless they are also frozen.
const user = Object.freeze(
});
user.profile.age = 26; // nested object can still change33. What is the difference between shallow copy and deep copy?
A shallow copy creates a new top-level object, but nested objects continue to be shared by reference.
A deep copy creates independent copies of nested values as well.
const original =
};
const copy = ;
copy.user.name = "Riya";
console.log(original.user.name); // RiyaThe spread syntax created only a shallow copy, so both objects still reference the same nested user object.
34. What is structuredClone() in JavaScript?
structuredClone() creates a deep clone of many JavaScript values using the structured clone algorithm.
const original =
};
const copy = structuredClone(original);
copy.user.name = "Riya";
console.log(original.user.name); // AmanIt can clone many built-in data structures that JSON-based cloning cannot handle correctly. However, not every JavaScript value is cloneable; functions, for example, cannot be cloned with structuredClone().
35. What are arrays in JavaScript?
An array is an ordered, zero-indexed collection used to store multiple values. JavaScript arrays are dynamic and can contain values of different types.
const values = [
10,
"hello",
true,
];Arrays are objects internally, so:
typeof []; // "object"
Array.isArray([]); // true36. What is the difference between map(), filter() and reduce()?
| Method | Purpose |
|---|---|
map() | Transforms every element and returns a new array |
filter() | Returns elements that satisfy a condition |
reduce() | Combines array elements into a single accumulated result |
const numbers = [1, 2, 3, 4];
numbers.map(n => n * 2);
// [2, 4, 6, 8]
numbers.filter(n => n % 2 === 0);
// [2, 4]
numbers.reduce((sum, n) => sum + n, 0);
// 1037. What is the difference between map() and forEach()?
map() creates and returns a new array containing the callback results. forEach() executes a callback for each element but returns undefined.
const numbers = [1, 2, 3];
const doubled = numbers.map(
n => n * 2
);
const result = numbers.forEach(
n => console.log(n)
);
console.log(result); // undefinedUse map() when the goal is to produce a transformed array. Use forEach() when the goal is mainly to perform an action for each item.
38. What is the difference between slice() and splice()?
slice() returns a selected portion of an array without modifying the original array.
splice() changes the original array by removing, replacing or inserting elements.
const numbers = [1, 2, 3, 4];
numbers.slice(1, 3);
// [2, 3]
numbers.splice(1, 2);
// numbers is now [1, 4]39. What is destructuring in JavaScript?
Destructuring extracts values from arrays or properties from objects into variables.
const user = ;
const = user;
const numbers = [10, 20];
const [first, second] = numbers;Destructuring can also provide default values, rename object properties and extract nested data.
40. What is the difference between spread and rest syntax?
Both use ..., but their purpose depends on context.
- Spread: expands values from an iterable or object into another structure.
- Rest: collects remaining values into an array or object.
const numbers = [1, 2, 3];
const copied = [...numbers];
function sum(...values)
sum(1, 2, 3); // 641. What is a Set in JavaScript?
A Set stores unique values. Adding the same value more than once does not create duplicate entries.
const values = new Set([
1,
2,
2,
3
]);
console.log([...values]);
// [1, 2, 3]Sets are useful for membership checks and removing duplicate primitive values from arrays.
42. What is a Map in JavaScript?
A Map stores key-value pairs and allows keys of any value type, including objects.
const map = new Map();
const user = ;
map.set(user, "Admin");
console.log(map.get(user));
// AdminUnlike ordinary object property keys, Map keys are not limited to strings and symbols.
43. What is the difference between Map and Object?
| Map | Object |
|---|---|
| Keys can be values of any type | Own property keys are strings or symbols |
Provides size | Requires another operation to count keys |
| Directly iterable | Usually iterated through methods such as Object.keys() or Object.entries() |
| Designed specifically for key-value collections | Also supports prototypes, methods and general object modelling |
Use the structure that best matches the problem rather than assuming one is universally better.
44. What are WeakMap and WeakSet?
WeakMap and WeakSet hold object references weakly, which means their presence in these collections does not by itself prevent the objects from being garbage collected.
- WeakMap: stores key-value pairs with weakly held object or non-registered symbol keys.
- WeakSet: stores weakly held objects or non-registered symbols.
Unlike Map and Set, WeakMap and WeakSet are not generally enumerable because entries can disappear when their keys or values are garbage collected.
45. What is optional chaining?
The optional chaining operator ?. safely accesses a property or method when the preceding value may be null or undefined.
const user = ;
console.log(
user.profile?.contact?.email
); // undefinedWithout optional chaining, accessing the missing nested property directly could throw a TypeError.
46. What is nullish coalescing?
The nullish coalescing operator ?? returns the right-hand value only when the left-hand value is null or undefined.
const count = 0;
console.log(count ?? 10);
// 0This differs from ||, which also treats values such as 0, "" and false as falsy.
47. What are template literals?
Template literals use backticks and support expression interpolation and multi-line strings.
const name = "Aman";
const message =
`Hello $ `;
console.log(message);
// Hello Aman48. What are tagged template literals?
A tagged template sends the parts of a template literal to a function before producing the final result.
function tag(strings, value) $ `;
}
const name = "aman";
tag`Hello $ `;
// "Hello AMAN"Tagged templates can be used for custom formatting, escaping or domain-specific template processing.
49. What is a Symbol in JavaScript?
A Symbol is a primitive value that is guaranteed to be unique when created with Symbol().
const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2);
// falseSymbols can be used as object property keys when a unique key is required.
50. What are private fields in JavaScript classes?
Private class elements use the # prefix and can only be accessed from within the class body where they are declared.
class Account
getBalance()
}Attempting to access #balance directly from outside the class results in a syntax error.
Asynchronous JavaScript Interview Questions
51. What is asynchronous programming in JavaScript?
Asynchronous programming allows JavaScript to start an operation and continue executing other code while waiting for that operation to complete.
This is important for operations such as:
- network requests;
- timers;
- file or database operations in server-side environments; and
- user-interface events.
JavaScript handles asynchronous behaviour using mechanisms such as callbacks, Promises and async/await.
52. What is the call stack in JavaScript?
The call stack tracks which functions are currently executing.
When a function is called, a frame is pushed onto the stack. When the function finishes, its frame is removed.
function first()
function second()
first();The stack grows as first() calls second() and then unwinds as each function returns.
53. What is the event loop in JavaScript?
The event loop coordinates the execution of asynchronous work by checking whether the call stack is empty and then allowing queued tasks to run according to the runtime’s scheduling rules.
In a browser environment, asynchronous operations such as timers and network requests are handled outside the JavaScript call stack. Their callbacks or promise reactions are queued and later executed when JavaScript is ready to process them.
54. What are Web APIs in the browser?
Browser Web APIs are capabilities provided by the browser environment rather than by the JavaScript language itself.
Examples include:
setTimeout();fetch();- DOM APIs;
- Geolocation;
- Web Storage; and
- Web Workers.
JavaScript can call these APIs, and the browser coordinates their asynchronous completion.
55. What is the difference between a task queue and a microtask queue?
In browser terminology, tasks and microtasks are scheduled differently.
- Tasks: include work such as timer callbacks and many event callbacks.
- Microtasks: include Promise reactions and
queueMicrotask()callbacks.
After the current JavaScript execution finishes, the runtime processes pending microtasks before moving on to the next task.
56. What will this JavaScript code output?
console.log("A");
setTimeout(() => , 0);
Promise.resolve().then(() => );
console.log("D");The output is:
A
D
C
BThe synchronous statements run first. The Promise callback runs as a microtask before the timer callback, which runs as a later task.
57. What is a Promise in JavaScript?
A Promise represents the eventual completion or failure of an asynchronous operation and its resulting value.
A Promise can be in one of three states:
- pending
- fulfilled
- rejected
const promise = new Promise((resolve, reject) => else
});58. What is Promise chaining?
Promise chaining means linking asynchronous operations using consecutive .then() calls.
fetch("/api/user")
.then(response => response.json())
.then(user => `);
})
.then(response => response.json())
.then(orders => )
.catch(error => );Each .then() returns a new Promise, allowing later steps to use the previous result.
59. What is the difference between then(), catch() and finally()?
then()handles fulfilled Promise results and can also provide a rejection handler.catch()handles rejection in a Promise chain.finally()runs after the Promise is settled, whether it was fulfilled or rejected.
loadData()
.then(data => )
.catch(error => )
.finally(() => );60. What is async/await in JavaScript?
async/await provides syntax for working with Promises in a way that can be easier to read than long Promise chains.
async function loadUser() An async function always returns a Promise. await pauses execution of that async function until the awaited value settles, without blocking the entire JavaScript runtime.
61. What is the difference between Promises and async/await?
async/await does not replace Promises; it is built on top of them.
| Promises | async/await |
|---|---|
Commonly use .then() and .catch() | Uses await inside an async function |
| Useful for composing multiple Promise operations directly | Often easier to read for sequential asynchronous steps |
Error handling often uses .catch() | Error handling commonly uses try...catch |
The choice is mainly about clarity and the control flow required.
62. How do you handle errors with async/await?
Errors can be handled with try...catch.
async function loadData() `
);
}
return await response.json();
} catch (error)
}A useful interview detail is that fetch() does not reject merely because the server returned an HTTP status such as 404 or 500, so response status should be checked explicitly when required.
63. What is Promise.all()?
Promise.all() waits for all supplied Promises to fulfil and returns their results in the same input order.
const [user, orders] = await Promise.all([
fetch("/api/user").then(r => r.json()),
fetch("/api/orders").then(r => r.json())
]);If any input Promise rejects, the Promise returned by Promise.all() rejects with that reason.
64. What is Promise.allSettled()?
Promise.allSettled() waits until every supplied Promise settles and returns the outcome of each Promise, regardless of whether it fulfilled or rejected.
const results = await Promise.allSettled([
Promise.resolve("A"),
Promise.reject("B")
]);
console.log(results);It is useful when every result matters and one failure should not prevent you from inspecting the others.
65. What is Promise.race()?
Promise.race() settles as soon as the first input Promise settles, whether that first result is a fulfilment or a rejection.
It can be used in patterns such as implementing a timeout race, although cancellation of the underlying work must be handled separately.
66. What is Promise.any()?
Promise.any() fulfils when the first input Promise fulfils. Rejections are ignored unless every input Promise rejects.
If all inputs reject, it rejects with an AggregateError.
67. What is callback hell?
Callback hell refers to deeply nested callback-based code that becomes difficult to read, reason about and maintain.
getUser(id, user => );
});
});Promises and async/await can often make this control flow clearer, although good function decomposition is still important.
68. What is queueMicrotask()?
queueMicrotask() schedules a function to run in the microtask queue after the current synchronous code completes.
console.log("start");
queueMicrotask(() => );
console.log("end");The output is:
start
end
microtask69. What is a generator function?
A generator function can pause its execution and later resume from the same point.
Generator functions are declared with function* and use yield to produce values.
function* numbers()
const iterator = numbers();
iterator.next(); //
iterator.next(); // Generators implement the iterator protocol and are useful for lazy sequences and custom iteration behaviour.
70. What are async iterators and for await…of?
Async iterators allow values to become available asynchronously. They can be consumed using for await...of.
async function* generateValues()
for await (const value of generateValues()) This pattern is useful when processing asynchronous sequences or streaming data.
DOM and Browser JavaScript Interview Questions
71. What is the DOM in JavaScript?
The Document Object Model (DOM) is the browser’s object representation of an HTML or XML document. JavaScript can use DOM APIs to read, modify, add or remove elements and respond to user interactions.
const heading =
document.querySelector("h1");
heading.textContent =
"Updated heading";The DOM is provided by the browser environment. It is not part of the JavaScript language specification itself.
72. What is the difference between getElementById() and querySelector()?
getElementById() selects an element using its ID. querySelector() accepts a CSS selector and returns the first matching element.
document.getElementById("profile");
document.querySelector(
".profile-card"
);querySelectorAll() can be used when all matching elements are required.
73. What is the difference between innerHTML, innerText and textContent?
| Property | What It Works With |
|---|---|
innerHTML | Reads or writes HTML markup inside an element |
innerText | Represents rendered text and is affected by styling/layout |
textContent | Reads or writes the text content of the node and its descendants |
When inserting untrusted user-controlled content, directly assigning it to innerHTML can create security risks such as cross-site scripting if the content is not handled safely.
74. What is event bubbling?
Event bubbling is the phase in which an event moves from its target element upward through its ancestors.
<div id="parent">
<button id="button">
Click
</button>
</div>If click handlers are attached to both elements, a click on the button can also reach the parent during the bubbling phase unless propagation is stopped.
75. What is event capturing?
Event capturing is the phase in which an event travels from outer ancestors toward the target before the target and bubbling phases.
element.addEventListener(
"click",
handler,
);Most event listeners use the bubbling phase by default unless capture is explicitly enabled.
76. What is event delegation?
Event delegation attaches a listener to a common ancestor instead of attaching separate listeners to many child elements.
document
.querySelector("#list")
.addEventListener("click", event =>
});It works because many events bubble through ancestor elements. Event delegation is useful for dynamic lists because newly added matching child elements can be handled by the existing parent listener.
77. What is the difference between event.target and event.currentTarget?
event.targetis the object on which the event was originally dispatched.event.currentTargetis the object whose event listener is currently running.
This distinction is particularly important when implementing event delegation.
78. What do preventDefault() and stopPropagation() do?
event.preventDefault() prevents the browser’s default action for an event when that action is cancelable.
event.stopPropagation() stops the event from continuing through the normal propagation path.
form.addEventListener(
"submit",
event =>
);Preventing a default action and stopping propagation are different operations.
79. What is debouncing?
Debouncing delays execution until a specified period has passed without another triggering event.
It is commonly used for:
- search suggestions;
- form validation;
- resize handling; and
- reducing repeated API calls while a user is typing.
function debounce(fn, delay) , delay);
};
}80. What is throttling?
Throttling limits a function so it runs at most once within a specified interval, even if the triggering event occurs many times.
It is commonly used for frequent events such as scrolling, resizing or pointer movement when continuous updates are required but executing on every event would be expensive.
81. What is the difference between debouncing and throttling?
| Debouncing | Throttling |
|---|---|
| Waits until repeated activity stops | Limits execution frequency while activity continues |
| Useful for search inputs | Useful for scrolling or resizing |
| May execute once after a burst of events | May execute repeatedly at controlled intervals |
82. What is localStorage?
localStorage is a browser storage API that stores string key-value pairs for an origin. Its data normally remains available across browser sessions until it is removed.
localStorage.setItem(
"theme",
"dark"
);
const theme =
localStorage.getItem("theme");Values are stored as strings, so structured data is commonly serialised with JSON.stringify() and parsed with JSON.parse().
83. What is sessionStorage?
sessionStorage is similar to localStorage, but its data is associated with a particular browser tab or page session and is removed when that session ends.
84. What is the difference between cookies, localStorage and sessionStorage?
| Storage | Typical Behaviour |
|---|---|
| Cookies | Small pieces of data that can be sent with HTTP requests depending on their attributes |
| localStorage | Origin-scoped browser storage that normally persists across sessions |
| sessionStorage | Origin- and tab/session-scoped storage that lasts for the page session |
Sensitive authentication data should not be stored casually in browser storage. The correct mechanism depends on the application’s security model.
85. What is JSON?
JSON, or JavaScript Object Notation, is a text-based data-interchange format used to represent structured data.
Although JSON syntax resembles JavaScript object literals, JSON is a separate data format with stricter syntax rules.
86. What is the difference between JSON.parse() and JSON.stringify()?
JSON.parse()converts valid JSON text into a JavaScript value.JSON.stringify()converts supported JavaScript values into JSON text.
const text =
' ';
const user =
JSON.parse(text);
const json =
JSON.stringify(user);Not every JavaScript value has a direct JSON representation. For example, functions and Symbols are not represented as ordinary JSON values.
87. What is a Web Worker?
A Web Worker allows JavaScript to run work in a separate worker context from the page’s main execution thread.
This is useful for computationally expensive tasks that could otherwise make the interface unresponsive.
Workers communicate with the main context through message passing and do not directly manipulate the page DOM.
88. What is a Service Worker?
A Service Worker is an event-driven worker that runs separately from a web page and can act as an intermediary between an application, the browser and the network.
Common uses include:
- offline caching;
- request interception;
- background-related web capabilities where supported; and
- push notifications.
Service Workers operate under specific security and lifecycle rules and are different from ordinary Web Workers.
89. What is the difference between a Web Worker and a Service Worker?
| Web Worker | Service Worker |
|---|---|
| Used mainly for off-main-thread computation | Designed around network interception and background web capabilities |
| Generally associated with the page that creates it | Has its own registration and lifecycle |
| Communicates through messages | Responds to events such as fetch-related events |
90. What are JavaScript modules?
JavaScript modules allow code to be split into separate files with explicit imports and exports.
// math.js
export function add(a, b)
// app.js
import from "./math.js";ES modules have their own module scope and support both named and default exports.
91. What is the difference between named exports and default exports?
A module can have multiple named exports, while it can have at most one default export.
// named
export const version = "1.0";
export function start()
// default
export default function App() Named imports use the exported names, while a default import can use a local name chosen by the importing module.
92. What is dynamic import in JavaScript?
Dynamic import uses import() to load a module asynchronously when it is needed.
const module =
await import("./analytics.js");
module.trackEvent();It is useful for conditional loading and code splitting because code does not always need to be loaded during the application’s initial execution.
93. What is the global object in JavaScript?
The global object provides access to global properties and functions for the current JavaScript environment.
Depending on the environment, older names include window in a browser window and global in Node.js. Modern JavaScript provides globalThis as a standard way to refer to the global object across environments.
console.log(globalThis);94. What is strict mode in JavaScript?
Strict mode enables a stricter set of JavaScript semantics that can turn some silent errors into exceptions and restrict certain error-prone behaviour.
"use strict";
function example() ES modules and class bodies already operate under strict-mode semantics, so an explicit "use strict" directive is not required there.
Read Also: Top 50 Programming Interview Questions and Answers
Advanced JavaScript Interview Questions and Answers
95. What is currying in JavaScript?
Currying transforms a function that accepts multiple arguments into a sequence of functions, each receiving one argument.
function add(a) ;
}
const addFive = add(5);
console.log(addFive(3));
// 8Currying can be useful when creating reusable partially configured functions.
96. What is function composition?
Function composition combines functions so that the output of one becomes the input of another.
const double = x => x * 2;
const addOne = x => x + 1;
const composed = x =>
addOne(double(x));
console.log(composed(5));
// 11Composition is common in functional programming because it allows larger transformations to be built from smaller functions.
97. What is a pure function?
A pure function returns the same output for the same inputs and does not cause observable side effects such as changing external state.
function add(a, b) Pure functions are easier to test and reason about because their result depends only on their inputs.
98. What is memoization?
Memoization caches the result of a function call so that the result can be reused when the same input appears again.
function memoize(fn)
const result = fn(value);
cache.set(value, result);
return result;
};
}Memoization can improve performance for expensive deterministic calculations, but the cache itself consumes memory and needs an appropriate keying strategy.
99. What is the difference between deep equality and reference equality?
Objects are compared by reference with ===, not by recursively comparing their properties.
const a = ;
const b = ;
const c = a;
console.log(a === b); // false
console.log(a === c); // trueA deep-equality comparison requires explicitly comparing nested values or using a suitable utility.
100. What are property descriptors in JavaScript?
JavaScript object properties have descriptors that control characteristics such as whether the property can be changed, enumerated or reconfigured.
Common descriptor fields include:
valuewritableenumerableconfigurablegetset
const user = ;
Object.defineProperty(
user,
"id",
);101. What are getters and setters in JavaScript?
Getters and setters provide property-style access while running functions when a property is read or assigned.
const user = $ `;
},
set fullName(value)
};102. What is a Proxy in JavaScript?
A Proxy wraps another object or function and allows selected fundamental operations to be intercepted through handler functions called traps.
const user = ;
const proxy = new Proxy(user, `
);
return Reflect.get(
target,
property
);
}
});
console.log(proxy.name);Proxies can be used for validation, logging, access control and reactive programming patterns.
103. What is the Reflect API?
Reflect provides static methods for common object operations such as reading, writing, deleting and defining properties.
const user = ;
Reflect.get(user, "name");
Reflect.set(
user,
"age",
25
);Reflect methods are especially useful alongside Proxy traps because many map closely to intercepted object operations.
JavaScript Performance and Memory Interview Questions
104. How does memory management work in JavaScript?
JavaScript automatically manages memory. Memory is allocated when values and objects are created, and garbage collection can reclaim memory for objects that are no longer reachable.
Developers do not manually free ordinary JavaScript memory, but they can still create memory problems by retaining unnecessary references.
105. What is garbage collection in JavaScript?
Garbage collection automatically identifies objects that are no longer reachable by the running program and makes their memory available for reuse.
Modern JavaScript engines use sophisticated garbage-collection strategies. At interview level, the important concept is reachability: an object can generally remain in memory while it is still reachable through active references.
106. What is a memory leak in JavaScript?
A memory leak occurs when memory remains reachable even though the application no longer needs the associated data.
Common causes can include:
- event listeners that are never removed when necessary;
- timers that continue running unnecessarily;
- large objects retained by closures;
- unbounded caches;
- references to detached DOM nodes; and
- accidental long-lived global references.
107. How can closures contribute to memory leaks?
A closure can keep variables from an outer scope reachable as long as the closure itself remains reachable.
This behaviour is normal and useful, but it can become a problem if a long-lived closure unnecessarily retains large objects that are no longer required.
function createHandler() ;
}As long as the returned function remains reachable, the data it closes over may also remain reachable.
108. How can you improve JavaScript performance in a web application?
The correct optimisation depends on the actual bottleneck. Common approaches include:
- measure performance before optimising;
- reduce unnecessary DOM operations;
- debounce or throttle high-frequency event handlers where appropriate;
- avoid unnecessary repeated calculations;
- split code so non-essential modules can load later;
- move suitable CPU-heavy work off the main thread with Web Workers;
- limit unnecessary network requests;
- release event listeners, timers and references when no longer needed; and
- use efficient data structures for the workload.
Performance optimisation should be based on profiling rather than assumptions.
109. What is lazy loading in JavaScript applications?
Lazy loading delays loading a resource or module until it is actually required.
For JavaScript modules, dynamic import() can be used to load code on demand.
button.addEventListener(
"click",
async () =>
);This can reduce the amount of JavaScript needed during the initial page load when the deferred functionality is not immediately required.
110. What is code splitting?
Code splitting breaks an application bundle into smaller chunks that can be loaded separately rather than sending all application code at once.
It is commonly combined with route-based or feature-based lazy loading in larger applications.
Read Also: Top Programming Languages to Learn in 2026
JavaScript Coding and Output-Based Interview Questions
111. How would you remove duplicate values from an array?
For primitive values, one concise approach is to use Set.
const numbers = [
1,
2,
2,
3,
3
];
const unique = [
...new Set(numbers)
];
console.log(unique);
// [1, 2, 3]For arrays of objects, a unique key such as id usually needs to be considered explicitly.
112. How would you reverse a string in JavaScript?
function reverseString(value)
console.log(
reverseString("hello")
);
// "olleh"For full Unicode correctness, string reversal can require additional care because user-perceived characters may contain multiple code points.
113. How would you check whether a string is a palindrome?
function isPalindrome(value)
console.log(
isPalindrome("level")
);
// trueIn an interview, clarify whether spaces, punctuation and letter case should be ignored before writing the solution.
114. How would you flatten a nested array?
For environments supporting Array.prototype.flat():
const nested = [
1,
[2, [3, 4]]
];
const flat =
nested.flat(Infinity);
console.log(flat);
// [1, 2, 3, 4]An interviewer may also ask you to implement flattening manually to test recursion.
115. How would you count the frequency of values in an array?
function countValues(values) ,
);
}
console.log(
countValues([
"a",
"b",
"a"
])
);
// 116. What will this code output?
console.log(typeof null);
console.log(typeof []);
console.log(typeof function () );The output is:
object
object
functiontypeof null === "object" is a historical JavaScript behaviour. Arrays are objects, while functions receive the special "function" result from typeof.
117. What will this code output?
console.log(1 + "2");
console.log("5" - 2);
console.log(true + 1);The output is:
12
3
2The results occur because JavaScript applies different coercion rules depending on the operator.
118. What will this closure code output?
function counter()
const first = counter();
const second = counter();
console.log(first());
console.log(first());
console.log(second());The output is:
1
2
1Each call to counter() creates a separate lexical environment, so first and second maintain independent values.
119. What is wrong with using var inside this loop?
for (var i = 0; i < 3; i++) , 0);
}The callbacks output:
3
3
3var is function-scoped, so all callbacks close over the same i binding. By the time the callbacks execute, the loop has completed and i is 3.
Using let creates a new binding for each loop iteration:
for (let i = 0; i < 3; i++) , 0);
}
// 0
// 1
// 2120. What will this Promise code output?
console.log("start");
Promise.resolve()
.then(() => );
setTimeout(() => , 0);
console.log("end");The output is:
start
end
promise
timerSynchronous code runs first, the Promise reaction runs as a microtask, and the timer callback runs in a later task.
How to Prepare for a JavaScript Interview
JavaScript interviews usually combine concept questions with code reading and short implementation problems. Preparation should therefore include both theory and hands-on practice.
1. Revise JavaScript Fundamentals
Be clear on the following concepts:
- Primitive and reference values
var,letandconst- Scope and lexical scope
- Hoisting and the Temporal Dead Zone
==vs===- Type coercion
null,undefinedandNaN- Functions and callbacks
2. Practise Closures, this and Prototypes
These concepts are frequently used to test whether you understand how JavaScript behaves beyond basic syntax.
- How closures retain access to their lexical scope
- How the value of
thisdepends on how a function is called - How arrow functions handle
this - How
call(),apply()andbind()work - How prototype chaining and JavaScript classes are related
3. Understand the JavaScript Event Loop
Understand how the call stack, browser APIs, tasks, microtasks and event loop work together when JavaScript handles asynchronous operations.
Practise output-based questions involving:
setTimeout()- Promises
queueMicrotask()async/await- Synchronous statements mixed with asynchronous callbacks
4. Practise Array and Object Methods
You should be comfortable working with commonly used array and object operations, including:
map()filter()reduce()find()andfindIndex()some()andevery()- Destructuring
- Spread and rest syntax
- Set and Map
- Shallow and deep copying
5. Prepare DOM and Browser Questions
For frontend JavaScript roles, revise DOM selection and manipulation, event propagation, event delegation, browser storage, Fetch API, Service Workers, Web Workers and JavaScript modules.
Also understand the distinction between the JavaScript language itself and APIs provided by the browser environment.
6. Practise JavaScript Coding Questions
Common JavaScript coding interview problems include:
- Reversing a string
- Checking whether a string is a palindrome
- Removing duplicate values from an array
- Flattening nested arrays
- Counting the frequency of values
- Implementing debounce or throttle
- Grouping array values
- Writing a simple memoization function
- Handling Promise-based asynchronous operations
While solving a coding question, explain the expected input, output, edge cases and the reasoning behind your solution.
7. Practise Output-Based JavaScript Questions
Output-based questions test whether you understand JavaScript execution behaviour instead of only remembering definitions.
Pay particular attention to:
- Scope and closures
- Type coercion
- The
thiskeyword varvsletinside loops- Promise and timer execution order
- Object references
8. Review the Job Description
The depth of JavaScript knowledge expected depends on the role. A frontend developer interview may focus more on DOM behaviour, browser APIs, events and performance, while a Node.js role may place greater emphasis on asynchronous execution, modules, APIs and server-side JavaScript.
If the job description mentions React, Angular, Vue or Node.js, prepare questions related to that framework or runtime separately in addition to JavaScript fundamentals.
Conclusion
JavaScript interview preparation should focus on understanding how the language behaves rather than memorising syntax. Start with scope, closures, functions, objects, prototypes and type coercion, then move to Promises, async/await, the event loop, DOM events and modern JavaScript features.
For experienced roles, also prepare performance, memory management, browser APIs and coding-based questions. When answering an output question, explain why JavaScript produces the result rather than stating only the final output.
FAQs
Experienced developers should prepare prototypes, this binding, call, apply and bind, Promise combinators, async/await, microtasks and tasks, event delegation, modules, memory management, performance, Proxy, Reflect, Web Workers and relevant browser APIs
Practise short problems involving arrays, strings, objects, closures, Promise handling and utilities such as debounce or throttle. Explain your assumptions, edge cases and reasoning while writing the solution.
Practise short problems involving arrays, strings, objects, closures, Promise handling and utilities such as debounce or throttle. Explain your assumptions, edge cases and reasoning while writing the solution
The event loop explains how JavaScript coordinates asynchronous work. Interviewers often combine timers, Promises and async/await in output questions to test whether candidates understand call-stack execution, microtasks and scheduled tasks.
Java and JavaScript are separate programming languages. Java is statically typed and class-based, while JavaScript is dynamically typed and uses prototype-based inheritance, with class syntax built on top of its prototype model.
The == operator may perform type coercion before comparison, while === compares values without that coercion. Strict equality is generally easier to reason about unless loose equality is deliberately required.


