Javascript Questions

Software Engineer | 50 questions | 2026

JavaScript Interview Questions and Answers

Closures, hoisting, this, promises, event loop. Tap a question to open the model answer, most asked first.

JavaScript interview questions for freshers 23

Q1FresherMost asked
Answer

What is the difference between var, let and const in JavaScript?

All three declare variables, but they differ in scope, hoisting and reassignment.

varletconst
ScopeFunctionBlockBlock
HoistingHoisted, initialised as undefinedHoisted, but in the temporal dead zone until declaredSame as let
Redeclare in same scopeAllowedErrorError
ReassignYesYesNo
  • const stops reassignment of the binding, not mutation of the value: const a = []; a.push(1) works.
  • Prefer const by default, let when you must reassign, and avoid var in new code.
  • A var declared at the top level of a script becomes a property of the global object; let and const do not.

What they are checking: Whether you understand scope and the temporal dead zone, not only the table

Q2FresherMost asked
Answer

What is hoisting in JavaScript?

Hoisting means declarations are processed before the code runs. So names are known in their scope before the line that declares them.

  • var is hoisted and initialised with undefined, so reading it early gives undefined.
  • let and const are hoisted but not initialised. Accessing them before the declaration throws a ReferenceError (the temporal dead zone).
  • Function declarations are hoisted with their body, so you can call them before they appear.
  • Function expressions and arrow functions follow the rule of the variable that holds them.
console.log(a); // undefined
var a = 1;
sayHi();        // works
function sayHi() { console.log("hi"); }
console.log(b); // ReferenceError
let b = 2;

What they are checking: Whether you know the difference between var, let and function hoisting

Q3FresherMost asked
Answer

What is a closure? Give a practical example.

A closure is a function together with the variables from the scope where it was created. The function keeps access to those variables even after the outer function has returned.

function makeCounter() {
  let count = 0;
  return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2

count is private: nothing outside can change it except through the returned function.

Common uses: data privacy, function factories, partial application, memoisation, and event handlers or callbacks that remember state. A common trap is capturing a loop variable declared with var. Also, a closure that holds a large object can keep it in memory longer than you expect.

What they are checking: Whether you can explain it simply and name real uses

Q4FresherMost asked
Answer

How does the this keyword work in JavaScript?

this is decided by how a function is called, not where it is written. Arrow functions are the exception.

  • Method call obj.fn(): this is obj.
  • Plain call fn(): this is undefined in strict mode and modules, the global object in sloppy mode.
  • new Fn(): this is the new object.
  • call, apply, bind: you set this yourself.
  • Arrow functions have no own this; they use the one from the enclosing scope.
  • In a DOM event handler (regular function), this is the element.
const user = { name: "Asha", hi() { return this.name; } };
user.hi();        // "Asha"
const f = user.hi;
f();              // this lost: undefined or error in strict mode

What they are checking: Whether you can predict this from the call site

Q5FresherMost asked
Answer

What is the difference between call, apply and bind?

All three set this for a function. They differ in when the function runs and how arguments are passed.

  • fn.call(thisArg, a, b): runs now, arguments listed one by one.
  • fn.apply(thisArg, [a, b]): runs now, arguments as an array.
  • fn.bind(thisArg, a): does not run; returns a new function with this (and optionally leading arguments) fixed.
function intro(city, country) { return `${this.name}, ${city}, ${country}`; }
const p = { name: "Sita" };
intro.call(p, "Pokhara", "Nepal");
intro.apply(p, ["Pokhara", "Nepal"]);
const bound = intro.bind(p, "Pokhara");
bound("Nepal");

A bound function cannot be re-bound to a different this.

What they are checking: Whether you know each one's timing and argument style

Q6FresherMost asked
Answer

What is the difference between == and === in JavaScript?

=== (strict equality) compares value and type with no conversion. == (loose equality) first converts both sides to a common type. This gives unexpected results.

0 == "0"        // true
0 === "0"       // false
null == undefined   // true
null === undefined  // false
NaN === NaN     // false
[] == false     // true

Use === by default. The one accepted use of == is value == null to test for both null and undefined. For NaN use Number.isNaN, and Object.is treats NaN as equal to itself and distinguishes +0 from -0.

What they are checking: Whether you know type coercion and default to strict equality

Q7FresherMost asked
Answer

What is the output of this loop, and how do you fix it? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }

It prints 3 3 3.

var is function scoped, so there is one shared i. The timeout callbacks run after the loop ends, when i is already 3.

Fixes:

// 1. let creates a new binding per iteration
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0); // 0 1 2

// 2. IIFE capturing the value
for (var i = 0; i < 3; i++) {
  ((j) => setTimeout(() => console.log(j), 0))(i);
}

This is the classic closure-in-loop question. The key point is that closures capture variables, not values.

What they are checking: Whether you connect closures and scope to a real bug

Q8FresherMost asked
Answer

What is a Promise and what are its states?

A Promise is an object representing the eventual result of an async operation. It has three states:

  • pending: the initial state.
  • fulfilled: finished with a value.
  • rejected: failed with a reason.

Once settled (fulfilled or rejected) it never changes. You consume it with .then(), .catch() and .finally(), and each returns a new promise, so calls chain.

const wait = (ms) => new Promise((res) => setTimeout(res, ms));
wait(100)
  .then(() => "done")
  .then(console.log)
  .catch(console.error)
  .finally(() => console.log("cleanup"));

An error thrown inside .then becomes a rejection of the returned promise. A missing .catch gives an unhandled rejection.

What they are checking: Whether you know the states and how chaining works

Q9FresherMost askedFree with sign-in
Answer

What are prototypes and how does prototypal inheritance work?

Every object has an internal link ([[Prototype]], readable with Object.getPrototypeOf) to another object. When you read a property that is not on the object, the engine follows this chain. It stops when it finds the property or reaches null.

Q10FresherMost askedFree with sign-in
Answer

What are the spread and rest operators?

Both use ..., but they do opposite jobs.

  • Spread expands an iterable or object into individual elements.
  • Rest collects remaining items into an array or object.
Q11FresherMost askedFree with sign-in
Answer

What is the difference between null and undefined?

undefined means a value has not been assigned: an uninitialised variable, a missing property, a missing argument, or a function with no return. null is a "no value" that a developer sets on purpose.

Q12FresherMost askedFree with sign-in
Answer

What are the data types in JavaScript, and how does type coercion work?

Seven primitives: string, number, bigint, boolean, undefined, null and symbol. Everything else is an object (arrays, functions, dates, maps).

Primitives are immutable and compared by value; objects are compared by reference.

Q13FresherMost askedFree with sign-in
Answer

Explain map, filter and reduce with examples.

They are array methods that return results without mutating the original array.

Q14FresherMost askedFree with sign-in
Answer

What is the difference between localStorage, sessionStorage and cookies?

localStoragesessionStorageCookies
LifetimeUntil clearedUntil the tab closesUntil expiry
SizeAbout 5 MBAbout 5 MBAbout 4 KB
Sent to serverNoNoYes, on every matching request
AccessJS onlyJS onlyJS, or HttpOnly (not JS)
ScopeOrigin...
Q15FresherMost askedFree with sign-in
Answer

What are optional chaining and nullish coalescing?

  • Optional chaining ?. stops and returns undefined if the value before it is null or undefined. It does not throw.
  • Nullish coalescing ?? returns the right side only when the left is null or undefined.
Q16FresherMost askedFree with sign-in
Answer

What is the difference between forEach and map?

map returns a new array built from the callback's return values. forEach returns undefined and is used only for side effects.

Q17FresherMost askedFree with sign-in
Answer

What is the temporal dead zone? What does this print? console.log(a); var a = 5; console.log(b); let b = 6;

The first console.log(a) prints undefined because var is hoisted and initialised to undefined. The second throws ReferenceError: Cannot access 'b' before initialization.

Q18FresherMost askedFree with sign-in
Answer

Explain destructuring and default parameters.

Destructuring unpacks values from arrays or objects into variables.

Q19FresherMost askedFree with sign-in
Answer

What is the output? console.log(0.1 + 0.2 === 0.3); console.log(typeof NaN); console.log([10, 9, 1].sort()); console.log([] + []);

  • false: numbers are IEEE 754 doubles, and 0.1 + 0.2 is 0.30000000000000004. Compare with a tolerance: Math.abs(a - b) < Number.EPSILON, or use integers (cents).
  • "number": NaN is a number type.
  • [1, 10, 9]: sort() without a comparator converts items to strings and compares them. Use sort((a, b) => a - b) for numbers.
  • "" (empty string): both arrays convert to empty strings, then concatenate.
Q20FresherMost askedFree with sign-in
Answer

What are higher-order functions and first-class functions?

Functions are first-class in JavaScript: they can be stored in variables, passed as arguments, and returned from other functions. A higher-order function either takes a function as an argument, returns one, or both.

Q21FresherMost askedFree with sign-in
Answer

What is the difference between a function declaration and a function expression?

A declaration is a statement with a name; a function expression produces a value and can be anonymous or named.

Q22FresherMost askedFree with sign-in
Answer

What is a pure function, and why does it matter?

A pure function returns the same output for the same input and has no side effects. It does not modify external state or its arguments, and it does no I/O.

Q23FresherFree with sign-in
Answer

What is strict mode and what does it change?

Strict mode is an opt-in version of JavaScript. You turn it on with "use strict"; at the top of a script or function. ES modules and class bodies are strict automatically.

JavaScript interview questions for experienced 19

Q24ExperiencedMost asked
Answer

Explain the JavaScript event loop.

JavaScript runs your code on one thread. The event loop is what lets it handle async work without blocking.

  1. Synchronous code runs on the call stack until it is empty.
  2. The host (browser or Node) handles async APIs (timers, network, DOM events). Later it queues a callback.
  3. Promise reactions and queueMicrotask callbacks go to the microtask queue. Timers and I/O callbacks go to the macrotask (task) queue.
  4. When the stack is empty, the loop runs all microtasks. Then it takes one macrotask and runs it. Then it runs microtasks again, and repeats. In browsers rendering happens between tasks.

What this means: a long synchronous loop freezes the page and delays timers. setTimeout(fn, 0) means "after the current code and microtasks". A microtask that keeps adding microtasks can block rendering.

What they are checking: Whether you can describe stack, queues and ordering, not only say single threaded

Q25ExperiencedMost asked
Answer

What is the output of this code, and why? console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4');

Output: 1 4 3 2.

  • 1 and 4 are synchronous, so they run first in order.
  • The promise callback is a microtask, so it runs as soon as the stack is empty: 3.
  • setTimeout is a macrotask, so it runs after the microtasks: 2, even with a delay of 0.

A harder variant adds async function f() { console.log('a'); await null; console.log('b'); }. Code before the first await runs synchronously; the code after it is a microtask. Explain by naming the stack, microtask queue and task queue.

What they are checking: Whether you can trace event loop ordering

Q26ExperiencedMost askedFree with sign-in
Answer

What is the difference between promises and async/await?

async/await is syntax built on top of promises. An async function always returns a promise. await pauses that function until a promise settles, without blocking the thread.

Q27ExperiencedMost askedFree with sign-in
Answer

What is the difference between microtasks and macrotasks?

Both are queues the event loop uses, but microtasks have higher priority.

  • Microtasks: promise .then/.catch/.finally callbacks, await continuations, queueMicrotask, MutationObserver.
  • Macrotasks: setTimeout, setInterval, DOM events, network and I/O callbacks, MessageChannel.
Q28ExperiencedMost askedFree with sign-in
Answer

What is the difference between debounce and throttle? Implement debounce.

Both limit how often a function runs during rapid events.

  • Debounce waits until events stop for N ms, then runs once. Good for search-as-you-type and window resize end.
  • Throttle runs at most once per N ms while events keep coming. Good for scroll, mousemove and drag.
Q29ExperiencedMost askedFree with sign-in
Answer

What is the difference between shallow copy and deep copy? How do you deep copy an object?

A shallow copy duplicates only the top level; nested objects are still shared references. A deep copy duplicates everything.

Q30ExperiencedMost askedFree with sign-in
Answer

How do arrow functions differ from regular functions?

Arrow functions are shorter, but the real differences are behavioural:

Q31ExperiencedMost askedFree with sign-in
Answer

What is event delegation and why is it useful?

Event delegation puts one listener on a parent element. It uses event bubbling to handle events from the children, and finds the source with event.target.

Q32ExperiencedMost askedFree with sign-in
Answer

What is the difference between Promise.all, allSettled, race and any?

All take an iterable of promises and return one promise.

Q33ExperiencedMost askedFree with sign-in
Answer

What is the difference between CommonJS and ES modules?

Both split code into files, but they differ in syntax and loading.

Q34ExperiencedMost askedFree with sign-in
Answer

What is the difference between event bubbling and capturing?

An event travels in three phases: capturing (window down to the target), target, then bubbling (target back up to window).

Q35ExperiencedMost askedFree with sign-in
Answer

What does this code print? const obj = { name: 'A', regular() { return this.name; }, arrow: () => this.name }; const fn = obj.regular; console.log(obj.regular(), obj.arrow(), fn());

  • obj.regular() gives "A": called as a method, so this is obj.
  • obj.arrow() gives undefined: an arrow function takes this from the place where the object literal sits (module or global scope), not from obj.
  • fn() loses the receiver. In strict mode or ES modules this is undefined, so reading .name throws a TypeError. In sloppy mode this is the global object. So it returns undefined (or "" in a browser, where window.name exists).
Q36ExperiencedMost askedFree with sign-in
Answer

What is currying? Write a curry function.

Currying turns a function of several arguments into a chain of functions. Each one takes one (or some) arguments. It enables reuse through partial application.

Q37ExperiencedMost askedFree with sign-in
Answer

How would you implement memoization?

Memoization caches results of a pure function keyed by its arguments, so repeated calls are instant.

Q38ExperiencedMost askedFree with sign-in
Answer

Implement Promise.all yourself.

Return a new promise. Track results by index so the order is kept. Resolve when the count reaches the length. Reject on the first failure.

Q39ExperiencedMost askedFree with sign-in
Answer

What are callbacks and callback hell? How do you avoid it?

A callback is a function passed to another function to be called later, often after async work. Callback hell is deeply nested callbacks that are hard to read, handle errors in and refactor.

Q40ExperiencedMost askedFree with sign-in
Answer

What is the difference between Object.freeze, Object.seal and const?

  • const prevents reassigning the variable. The object it points to can still change.
  • Object.freeze(obj) makes the object immutable at the top level: no add, delete or change of properties.
  • Object.seal(obj) blocks adding and deleting properties, but existing ones can still be changed.
  • Object.preventExtensions(obj) blocks only adding.
Q41ExperiencedMost askedFree with sign-in
Answer

How does JavaScript garbage collection work, and what causes memory leaks?

Engines use mark-and-sweep: starting from roots (global object, stack), they mark everything reachable and free the rest. Reference counting alone fails on cycles, so it is not used.

Q42ExperiencedMost askedFree with sign-in
Answer

What does the new keyword do, and how do classes work in JavaScript?

new Fn(...) does four things: creates an empty object and links its prototype to Fn.prototype. It calls Fn with this set to that object. It returns the object (unless the function returns another object).

Scenario based JavaScript interview questions 8

Q43ExperiencedMost askedScenarioFree with sign-in
Answer

In a search box, users type fast and old responses sometimes overwrite newer results. How do you fix this race condition?

The problem: requests can return out of order. A slow response for an old query arrives last and wins.

Q44ExperiencedMost askedScenarioFree with sign-in
Answer

How do you handle errors in async code, and what happens with unhandled promise rejections?

Use try/catch around await, or .catch() on promise chains. A thrown error in an async function becomes a rejected promise.

Q45ExperiencedMost askedScenarioFree with sign-in
Answer

Our single page app slows down and memory grows the longer a user keeps it open. How do you find and fix the leak?

Approach: reproduce, measure, compare, fix.

Q46ExperiencedMost askedScenarioFree with sign-in
Answer

A page freezes for seconds when a user clicks a button that processes a large array. How would you fix it?

The work runs on the main thread, so it blocks rendering and input. Confirm with the DevTools Performance tab (a long task).

Q47ExperiencedMost askedScenarioFree with sign-in
Answer

You must call an API for 1,000 ids, but the server allows only 5 concurrent requests. How do you implement that?

Fire all 1,000 at once and you will hit rate limits or exhaust the browser. Use a pool: start up to 5 workers that each pull the next id until none are left.

Q48ExperiencedMost askedScenarioFree with sign-in
Answer

An API call fails randomly. How would you implement retry with exponential backoff?

Retry only temporary failures (network errors, 5xx, 429). Wait longer each time. Add jitter (a small random delay) so many clients do not retry together. Limit the number of attempts. Do not retry 4xx client errors. Retry non-idempotent requests (like POST) only if the server supports idempotency keys.

Q49ExperiencedMost askedScenarioFree with sign-in
Answer

Given an array of objects, how do you remove duplicates by id and group items by a field?

Use a Map or object for O(n) work instead of nested loops.

Q50ExperiencedMost askedScenarioFree with sign-in
Answer

Scenario: users sometimes double click a Submit button and create two orders. How do you prevent it?

Fix it on both sides, because client checks alone can be bypassed.

Client:

  • Disable the button and show a spinner as soon as the submit starts. Enable it again in finally.
  • Guard with a flag so a second handler call returns early.
Test yourself on JavaScriptQuick MCQs, right or wrong shown instantlyStart

More Software Engineer interview questions