Skip to content
  1. Home
  2. Interview Questions
  3. JavaScript
Popular Languages

JavaScript Interview Questions and Answers (2026) — Freshers to 5+ Years

The JavaScript interview questions asked in 2026, from hoisting, scope and closures for freshers to the event loop, promises, async patterns, memory leaks and performance for developers with 4–5+ years of experience. Each answer has a quick answer and runnable code.

Updated November 2026 Reviewed by Abhishek Kumar 72 min read
60Questions
15Freshers
16Intermediate
11Experienced

Key takeaways

  • Freshers: var/let/const, hoisting, closures, this, == vs ===, array methods and promises are guaranteed questions.
  • 4–5+ years: expect event-loop output puzzles, microtasks vs macrotasks, writing debounce/Promise.all from scratch, memory leaks, prototypes and module patterns.
  • Coding rounds often ask you to implement polyfills (map, bind, Promise.all), deep clone, flatten and debounce/throttle — all covered below.

What is JavaScript, and why do interviewers ask about it?

JavaScript is the language of the web — it runs in every browser, on servers with Node.js, Deno and Bun, in mobile apps through React Native and in desktop apps through Electron. Almost every frontend, full-stack and many backend interviews include a JavaScript round.

These JavaScript interview questions follow the way real interviews progress: language fundamentals for freshers, then closures, prototypes, promises and the DOM for mid-level developers, and performance, security and browser internals for senior engineers — plus the coding problems interviewers ask you to solve live.

Why companies hire for JavaScript

  • Every frontend and full-stack role tests JavaScript in depth
  • The same language powers React, Next.js, Node.js and React Native
  • Async programming and closures are favourite interview filters
  • Strong JavaScript fundamentals make learning any framework faster

Basic JavaScript Interview Questions for Freshers

15 questions

Start here if you are a fresher or switching to JavaScript. These fundamentals are asked in almost every first-round and campus interview.

BeginnerJavaScript
Quick answerJavaScript is a high-level, dynamically typed, single-threaded programming language with first-class functions and an event-driven, non-blocking concurrency model. It is standardised as ECMAScript (yearly releases: ES2015/ES6 onward).

Where it runs:

  • Browsers — DOM manipulation, UI logic, SPAs with React, Angular and Vue
  • Servers — Node.js, Deno, Bun (APIs, real-time apps, tooling)
  • Mobile and desktop — React Native, Ionic, Electron
  • Edge and serverless — Cloudflare Workers, Vercel and Netlify functions

Modern engines such as V8 parse JavaScript, then JIT-compile hot code to machine code, which is why it is fast despite being dynamic.

How interviewers ask it“Let's start with the basics — how would you explain the data types in JavaScript?”

What are the data types in JavaScript?

BeginnerJavaScript
Quick answerJavaScript has 7 primitive types — string, number, bigint, boolean, undefined, null and symbol — and one non-primitive type, object (which includes arrays, functions, dates, maps and so on). Primitives are immutable and compared by value; objects are compared by reference.
JavaScript
typeof "hi";        // "string"
typeof 42;          // "number"
typeof 10n;         // "bigint"
typeof Symbol();    // "symbol"
typeof undefined;   // "undefined"
typeof null;        // "object"  ← historical bug
typeof [];          // "object"  → use Array.isArray([])
typeof () => {};    // "function" (still an object)
BeginnerJavaScript
varletconst
ScopeFunctionBlockBlock
HoistingHoisted, initialised to undefinedHoisted, in the temporal dead zone until declaredSame as let
Re-declare in same scopeYesNoNo
Re-assignYesYesNo

const stops re-assignment, not mutation: const arr = []; arr.push(1) is allowed. Modern code uses const by default, let when the value must change, and never var.

JavaScript
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i));  // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j));  // 0 1 2 (new binding per iteration)

How interviewers ask it“In simple words, what is hoisting? Explain it like you would to a new teammate.”

What is hoisting in JavaScript?

BeginnerJavaScript
Quick answerHoisting is JavaScript's behaviour of processing declarations before code runs, so names are known in their scope before the line where they appear. Function declarations are fully hoisted (callable before their definition); var is hoisted and initialised to undefined; let, const and class are hoisted but stay in the temporal dead zone (TDZ) until their declaration line runs, so accessing them earlier throws a ReferenceError.
JavaScript
greet();                 // works: function declarations are hoisted
function greet() { console.log("hi"); }

console.log(a);          // undefined
var a = 1;

console.log(b);          // ReferenceError (TDZ)
let b = 2;

How interviewers ask it“Can you compare == and ===? Where do people usually confuse them?”

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

BeginnerJavaScript
Quick answer=== (strict equality) compares value and type with no conversion. == (loose equality) applies type coercion first, which leads to surprising results. Use === everywhere; the one accepted idiom is x == null, which checks for both null and undefined.
JavaScript
0 == "0";          // true  (string coerced to number)
0 === "0";         // false
null == undefined; // true
null === undefined;// false
[] == false;       // true  (!)
NaN === NaN;       // false → use Number.isNaN(x)

How interviewers ask it“Let's start with the basics — how would you explain truthy and falsy values in JavaScript?”

What are truthy and falsy values?

BeginnerJavaScript
Quick answerIn a boolean context, JavaScript converts values to true or false. There are exactly 8 falsy values: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy — including "0", "false", [] and {}.
JavaScript
const count = 0;
console.log(count || 10);   // 10 — || treats 0 as missing (often a bug)
console.log(count ?? 10);   // 0  — ?? only falls back for null/undefined

How interviewers ask it“Can you compare null and undefined? Where do people usually confuse them?”

What is the difference between null and undefined?

BeginnerJavaScript
Quick answerundefined means a value was never assigned — uninitialised variables, missing object properties, missing function arguments and functions without return. null is an intentional "no value" that a developer assigns. typeof null is "object" (a legacy bug), while typeof undefined is "undefined". In JSON, undefined properties are dropped, but null is kept.
BeginnerJavaScript
  • Declaration: function add(a, b) {} — hoisted, has its own this and arguments
  • Expression: const add = function (a, b) {} — not hoisted (the variable is), can be anonymous or named
  • Arrow function: const add = (a, b) => a + b — concise, with no own this, arguments or prototype, and it can't be used with new
JavaScript
const counter = {
  count: 0,
  start() {
    setInterval(() => this.count++, 1000);   // arrow keeps `this` = counter
  },
};

Don't use arrow functions as object methods that need this to refer to the object.

BeginnerJavaScript
Quick answerScope decides where a variable is accessible. JavaScript has global, function and block scope (let/const inside {}), plus module scope in ES modules. Scope is lexical: it is fixed by where code is written. When a variable is used, the engine looks in the current scope, then the outer scope, and so on up to the global scope — that's the scope chain. If the name isn't found anywhere, a ReferenceError is thrown.

How interviewers ask it“Let's start with the basics — how would you explain template literals in JavaScript?”

What are template literals?

BeginnerJavaScript
Quick answerTemplate literals use backticks and support interpolation (${expr}), multi-line strings and tagged templates — functions that process the template (used by styled-components, GraphQL gql and safe SQL builders).
JavaScript
const user = { name: "Asha", score: 92 };
const msg = `Hi ${user.name},
your score is ${user.score >= 90 ? "excellent" : "good"}.`;

How interviewers ask it“Let's start with the basics — how would you explain the spread and rest operators in JavaScript?”

What are the spread and rest operators?

BeginnerJavaScript
Quick answerBoth use.... Spread expands an iterable or object into individual elements; rest collects remaining elements into an array or object.

Both use .... Spread expands an iterable or object into individual elements; rest collects remaining elements into an array or object.

JavaScript
const a = [1, 2], b = [3, 4];
const merged = [...a, ...b];                 // spread: [1, 2, 3, 4]
const user = { name: "Ravi", role: "dev" };
const updated = { ...user, role: "lead" };   // shallow copy + override

function sum(...nums) {                      // rest parameter
  return nums.reduce((t, n) => t + n, 0);
}
const { name, ...others } = user;            // rest in destructuring

Spread makes shallow copies — nested objects are still shared.

How interviewers ask it“In simple words, what is destructuring? Explain it like you would to a new teammate.”

What is destructuring in JavaScript?

BeginnerJavaScript
Quick answerDestructuring unpacks values from arrays or properties from objects into variables, with support for defaults, renaming and nesting.
JavaScript
const [first, , third = 0] = [10, 20];           // 10, skips 20, default 0
const { id, profile: { city = "Pune" } = {} } = user;
function createUser({ name, role = "viewer" }) { /* named-parameter style */ }
[a, b] = [b, a];                                  // swap without a temp variable
BeginnerJavaScript
Quick answerThey are non-mutating array methods that take a callback:
  • map transforms each element and returns a new array of the same length
  • filter keeps the elements for which the callback returns truthy
  • reduce folds the array into a single value using an accumulator
JavaScript
const orders = [{ amount: 500, paid: true }, { amount: 300, paid: false }, { amount: 200, paid: true }];

const paidTotal = orders
  .filter(o => o.paid)
  .map(o => o.amount)
  .reduce((sum, amt) => sum + amt, 0);   // 700

Always pass an initial value to reduce — without one it throws on an empty array.

BeginnerJavaScript
Quick answerJSON (JavaScript Object Notation) is a text format for data exchange: double-quoted keys and strings, and only strings, numbers, booleans, null, arrays and objects. Functions, undefined, Symbol, Date objects (which become strings), Map and Set don't survive a round trip.
JavaScript
const json = JSON.stringify({ id: 1, tags: ["js"] }, null, 2);   // pretty-printed
const obj = JSON.parse(json);
try { JSON.parse("{bad json}"); } catch (e) { console.error("Invalid JSON", e.message); }
BeginnerJavaScript
Quick answerThe Document Object Model is the browser's tree representation of an HTML page that JavaScript can read and modify. You select elements (querySelector), change content or attributes, and respond to user actions with addEventListener.
JavaScript
const btn = document.querySelector("#save");
const status = document.querySelector("#status");

btn.addEventListener("click", (event) => {
  event.preventDefault();
  status.textContent = "Saved ✓";            // textContent is safe; innerHTML can cause XSS
  status.classList.add("ok");
});

Intermediate JavaScript Interview Questions

16 questions

Questions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with JavaScript.

IntermediateJavaScript
Quick answerA closure is a function bundled with references to the variables of the scope where it was created, so it can keep using them after that outer function has returned. Closures enable private state, function factories, memoisation, event handlers and module patterns.
JavaScript
function createCounter() {
  let count = 0;                       // private — not reachable from outside
  return {
    increment: () => ++count,
    reset: () => { count = 0; },
  };
}
const c = createCounter();
c.increment(); c.increment();          // 2
Likely follow-up questions
  • What is a "stale closure" in React hooks? (A callback that captured an old state value because it wasn't re-created when dependencies changed.)

How interviewers ask it“How does prototypal inheritance work under the hood? Take me through it step by step.”

How does prototypal inheritance work?

IntermediateJavaScript
Quick answerEvery object has an internal link ([[Prototype]]) to another object. When you read a property that isn't on the object itself, JavaScript walks this prototype chain until it finds it or reaches null. Methods defined on Constructor.prototype are shared by all instances, which saves memory. ES6 class syntax is built on top of this mechanism.
JavaScript
const animal = { speak() { return `${this.name} makes a sound`; } };
const dog = Object.create(animal);      // dog.[[Prototype]] = animal
dog.name = "Rex";
dog.speak();                            // found on the prototype
Object.getPrototypeOf(dog) === animal;  // true
IntermediateJavaScript
Quick answerClasses are mostly syntax over prototypes — methods go on ClassName.prototype — with extras: they always run in strict mode, must be called with new, support extends/super, static members, getters and setters, and true private fields and methods (#field).
JavaScript
class Account {
  #balance = 0;                              // truly private
  static count = 0;
  constructor(owner) { this.owner = owner; Account.count++; }
  deposit(amount) {
    if (amount <= 0) throw new RangeError("Invalid amount");
    this.#balance += amount;
    return this;
  }
  get balance() { return this.#balance; }
}
class Savings extends Account {
  addInterest(rate) { return this.deposit(this.balance * rate); }
}
IntermediateJavaScript
Quick answerAll three handle asynchronous results:
  • Callbacks pass a function to be called later — simple, but nesting leads to "callback hell" and inconsistent error handling
  • Promises represent a future value (pending → fulfilled or rejected), can be chained with .then(), and have centralised .catch()
  • async/await is syntax over promises that reads like synchronous code, with try/catch for errors
JavaScript
// Promise chain
fetch("/api/user").then(r => r.json()).then(u => render(u)).catch(showError);

// async/await
async function load() {
  try {
    const res = await fetch("/api/user");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    render(await res.json());
  } catch (err) {
    showError(err);
  }
}

How interviewers ask it“How would you run async tasks in parallel instead of one after another? Walk me through your approach.”

How do you run async tasks in parallel instead of one after another?

IntermediateJavaScript
Quick answerCalling await on each task in turn runs them sequentially. Start all the promises first, then await them together with Promise.all (fails fast), Promise.allSettled (keeps every result), Promise.race (first to settle) or Promise.any (first to fulfil).
JavaScript
// Sequential: ~3 seconds if each call takes 1 second
const a = await getUser(); const b = await getOrders(); const c = await getCart();

// Parallel: ~1 second
const [user, orders, cart] = await Promise.all([getUser(), getOrders(), getCart()]);

// Partial results are acceptable
const results = await Promise.allSettled(urls.map(u => fetch(u)));
const ok = results.filter(r => r.status === "fulfilled").map(r => r.value);
IntermediateJavaScript
Quick answerWhen an event fires, it goes through three phases: capturing (window → target), target, then bubbling (target → window). Listeners run in the bubbling phase by default. Event delegation attaches one listener to a parent and uses event.target to handle events from many children — including ones added later — which is efficient for long or dynamic lists.
JavaScript
document.querySelector("#todo-list").addEventListener("click", (e) => {
  const btn = e.target.closest("button.delete");
  if (!btn) return;
  btn.closest("li").remove();
});
// e.stopPropagation() stops bubbling; e.preventDefault() stops the default action

How interviewers ask it“How is a shallow copy different from a deep copy, and when does the difference matter in practice?”

What is the difference between a shallow copy and a deep copy?

IntermediateJavaScript
Quick answerA shallow copy duplicates only the top level, so nested objects are still shared references (spread, Object.assign, Array.from, slice). A deep copy duplicates everything recursively. Use structuredClone() — built into modern browsers and Node.js — which handles nested objects, Dates, Maps, Sets and circular references (but not functions or DOM nodes).
JavaScript
const original = { user: { name: "Asha" }, tags: ["a"] };
const shallow = { ...original };
shallow.user.name = "Ravi";            // also changes original.user.name!
const deep = structuredClone(original);
deep.user.name = "Neha";               // original untouched
IntermediateJavaScript
  • Map: key-value pairs with keys of any type, insertion order kept, a size property, and better performance than plain objects for frequent additions and deletions
  • Set: a collection of unique values — great for de-duplication and membership checks
  • WeakMap / WeakSet: keys must be objects and are held weakly, so entries disappear when a key is garbage-collected; they are not iterable. Use them for private data or caches attached to objects (DOM nodes, for example) without causing memory leaks
JavaScript
const visits = new Map();
visits.set(userObj, 3);
const unique = [...new Set([1, 2, 2, 3])];   // [1, 2, 3]
const meta = new WeakMap();
meta.set(domNode, { tooltip: "Save" });      // freed with the node
IntermediateJavaScript
Quick answerOptional chaining safely reads deeply nested properties or calls methods, returning undefined instead of throwing when something in the chain is null or undefined. Nullish coalescing provides a default only for null/undefined — unlike ||, it keeps valid falsy values such as 0 and "".
JavaScript
const city = order?.customer?.address?.city ?? "Not provided";
const qty = input.quantity ?? 1;        // 0 stays 0
user.onLogin?.();                        // call only if defined
settings.theme ??= "light";             // assign only if null/undefined
IntermediateJavaScript
Quick answerAll three set this explicitly. call invokes the function immediately with arguments listed individually; apply invokes it immediately with arguments as an array; bind returns a new function with this (and optionally the first arguments) permanently fixed.
JavaScript
function introduce(greeting, punct) { return `${greeting}, I'm ${this.name}${punct}`; }
const p = { name: "Asha" };
introduce.call(p, "Hi", "!");        // "Hi, I'm Asha!"
introduce.apply(p, ["Hello", "."]);  // "Hello, I'm Asha."
const hiAsha = introduce.bind(p, "Hey");
hiAsha("?");                          // "Hey, I'm Asha?"

How interviewers ask it“How would you explain generators and iterators to a junior engineer, and what do people most often get wrong?”

What are generators and iterators?

IntermediateJavaScript
Quick answerAn iterator is an object with a next() method that returns { value, done }; an iterable has a [Symbol.iterator] method (arrays, strings, Maps and Sets do), which is what lets for...of and spread work. A generator (function*) is an easy way to create iterators: yield pauses execution and resumes on the next next() call — useful for lazy sequences and pagination.
JavaScript
function* idGenerator(prefix) {
  let i = 1;
  while (true) yield `${prefix}-${i++}`;
}
const ids = idGenerator("ORD");
ids.next().value;   // "ORD-1"
ids.next().value;   // "ORD-2"

async function* pages(url) {             // async generator for paginated APIs
  for (let next = url; next; ) {
    const res = await (await fetch(next)).json();
    yield res.items; next = res.nextUrl;
  }
}

How interviewers ask it“Explain currying in JavaScript in detail — what should a new team member understand about it?”

What is currying in JavaScript?

IntermediateJavaScript
Quick answerCurrying transforms a function of several arguments into a chain of functions that each take one argument. It enables partial application and reusable, specialised functions.
JavaScript
const curry = (fn) => function curried(...args) {
  return args.length >= fn.length ? fn.apply(this, args) : (...next) => curried.apply(this, [...args, ...next]);
};
const discount = curry((rate, price) => price * (1 - rate));
const festiveSale = discount(0.2);
festiveSale(1000);   // 800
IntermediateJavaScript
Quick answerfetch returns a promise that resolves for any HTTP response — including 404 and 500 — so check res.ok. Use AbortController (or AbortSignal.timeout) to cancel requests and add timeouts.
JavaScript
async function getJSON(url, ms = 5000) {
  const res = await fetch(url, { signal: AbortSignal.timeout(ms), headers: { Accept: "application/json" } });
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  return res.json();
}

const controller = new AbortController();
fetch("/api/search?q=java", { signal: controller.signal });
controller.abort();                       // cancels it (e.g. when a new search starts)

How interviewers ask it“How would you explain strict mode to a junior engineer, and what do people most often get wrong?”

What is strict mode?

IntermediateJavaScript
Quick answer"use strict" opts into a safer subset of JavaScript: assigning to undeclared variables throws instead of creating globals; this is undefined in plain function calls rather than the global object; duplicate parameter names and with are forbidden; and some silent failures become errors. ES modules and class bodies are always in strict mode.

How interviewers ask it“How does garbage collection work under the hood? Take me through it step by step.”

How does garbage collection work in JavaScript?

IntermediateJavaScript
Quick answerJavaScript engines use automatic mark-and-sweep garbage collection: starting from roots (global object, the current call stack, closures in use), they mark everything reachable and free the rest. V8 is generational — a fast "scavenger" for short-lived objects and a mark-compact collector for long-lived ones, mostly running concurrently. You can't free memory manually; you avoid leaks by dropping references (removing listeners, clearing timers, bounding caches).

Advanced JavaScript Interview Questions for Experienced Developers

11 questions

Senior-level JavaScript questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.

AdvancedJavaScript
Quick answerReflow (layout) recalculates element positions and sizes; repaint redraws pixels. Changing geometry (width, font size, adding elements) triggers reflow, which is expensive. Layout thrashing happens when code alternates DOM writes with reads of layout properties (offsetHeight, getBoundingClientRect), forcing synchronous reflows in a loop.
JavaScript
// Bad: read-write-read-write → a forced reflow on every iteration
items.forEach(el => { el.style.width = el.offsetWidth + 10 + "px"; });

// Good: batch reads, then batch writes
const widths = items.map(el => el.offsetWidth);
requestAnimationFrame(() => items.forEach((el, i) => { el.style.width = widths[i] + 10 + "px"; }));

Animate transform and opacity (handled by the compositor) instead of top, left or width.

How interviewers ask it“How would you prevent XSS in a JavaScript application? Walk me through your approach.”

How do you prevent XSS in a JavaScript application?

AdvancedJavaScript
Quick answerCross-site scripting happens when untrusted input is executed as code in your page. Defences:
  • Insert text with textContent or framework bindings (React escapes by default); avoid innerHTML, document.write and eval
  • If you must render HTML, sanitise it (DOMPurify)
  • Set a strict Content-Security-Policy (no inline scripts, nonces/hashes), and consider Trusted Types
  • Keep sessions in HttpOnly cookies so injected scripts can't steal them
  • Validate and encode on the server too
JavaScript
el.innerHTML = userComment;                     // ❌ XSS risk
el.textContent = userComment;                   // ✅ rendered as text
el.innerHTML = DOMPurify.sanitize(userHtml);    // ✅ when HTML is required
AdvancedJavaScript
Quick answerBrowsers enforce the same-origin policy: scripts can't read responses from another origin (scheme + host + port) unless that server allows it with CORS headers such as Access-Control-Allow-Origin. For non-simple requests (custom headers, PUT/DELETE, JSON content type) the browser first sends an OPTIONS preflight request. A CORS error means the server didn't allow your origin — it must be fixed on the server (or via a proxy), not in frontend code. CORS protects users in browsers; it is not API authentication.
AdvancedJavaScript
Quick answerWeb Workers run JavaScript on a background thread, so heavy computation — parsing large files, image processing, encryption, data crunching — doesn't freeze the UI. Workers have no DOM access and communicate with postMessage (data is structured-cloned, or transferred with zero copies using Transferable objects).
JavaScript
// main.js
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
worker.postMessage(largeCsvText);
worker.onmessage = (e) => renderChart(e.data);

// worker.js
self.onmessage = (e) => self.postMessage(parseAndAggregate(e.data));
AdvancedJavaScript
Quick answerA Proxy wraps an object and intercepts operations (get, set, delete, function calls) through traps; Reflect provides the default behaviour for those operations. They power reactive frameworks (Vue 3, MobX), validation layers, logging and API clients.
JavaScript
const validated = new Proxy({}, {
  set(target, key, value) {
    if (key === "age" && (!Number.isInteger(value) || value < 0)) throw new TypeError("Invalid age");
    return Reflect.set(target, key, value);
  },
});
validated.age = 30;      // ok
validated.age = -5;      // TypeError
AdvancedJavaScript
Quick answerA Symbol is a unique, immutable primitive often used as a property key that can't clash with other keys and is hidden from for...in and JSON.stringify. Well-known symbols let you customise language behaviour: Symbol.iterator (make objects iterable), Symbol.asyncIterator, Symbol.toPrimitive and Symbol.hasInstance.
JavaScript
class Range {
  constructor(from, to) { this.from = from; this.to = to; }
  *[Symbol.iterator]() { for (let i = this.from; i <= this.to; i++) yield i; }
}
[...new Range(1, 4)];   // [1, 2, 3, 4]

How interviewers ask it“How would you optimise the load performance of a JavaScript-heavy web app? Walk me through your approach.”

How do you optimise the load performance of a JavaScript-heavy web app?

AdvancedJavaScript
  • Ship less JavaScript: code-split by route (import()), tree-shake, remove unused dependencies, analyse the bundle
  • Load smarter: defer/async scripts, preload critical resources, lazy-load below-the-fold components and images
  • Render on the server: SSR/SSG, streaming and partial hydration (Next.js, Astro) for faster LCP
  • Cache: content-hashed filenames with long cache headers, a CDN, service workers
  • Keep the main thread free: break up long tasks, move heavy work to Web Workers — this improves INP
  • Measure: Lighthouse, Web Vitals in real-user monitoring, the DevTools Performance panel

How interviewers ask it“How is debounce different from throttle, and when does the difference matter in practice?”

What is the difference between debounce and throttle in practical terms?

AdvancedJavaScript
Quick answerBoth limit how often a function runs during rapid events. Debounce waits until events stop for N ms and then runs once — ideal for search-as-you-type, auto-save and window resize. Throttle runs at most once every N ms while events keep firing — ideal for scroll tracking, drag and analytics. The scenario section at the end of this page has full implementations.
AdvancedJavaScript
Quick answerBefore ES modules, the module pattern used an IIFE (immediately invoked function expression) and closures to create private state and expose a public API without polluting the global scope. ES modules do this natively: each file has its own scope, with explicit export/import, static analysis for tree-shaking, and support for top-level await.
JavaScript
// Classic module pattern
const CartModule = (function () {
  const items = [];                                   // private
  return { add: (i) => items.push(i), count: () => items.length };
})();

// ES module
// cart.js
const items = [];
export const add = (i) => items.push(i);
export const count = () => items.length;
AdvancedJavaScript
Quick answerAll number values are IEEE-754 double-precision floats, so some decimals can't be represented exactly (0.1 + 0.2!== 0.3), and integers are only safe up to Number.MAX_SAFE_INTEGER (2^53 − 1). Use BigInt for larger integers (IDs, cryptography), and integer minor units (paise or cents) or a decimal library for money.

All number values are IEEE-754 double-precision floats, so some decimals can't be represented exactly (0.1 + 0.2 !== 0.3), and integers are only safe up to Number.MAX_SAFE_INTEGER (2^53 − 1). Use BigInt for larger integers (IDs, cryptography), and integer minor units (paise or cents) or a decimal library for money.

JavaScript
0.1 + 0.2;                                        // 0.30000000000000004
Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON;       // true
9007199254740993n + 1n;                           // 9007199254740994n
(1999 + 2999) / 100;                              // store ₹19.99 + ₹29.99 as paise

How interviewers ask it“How would you explain the latest JavaScript (ES2023–ES2025) features worth knowing to a junior engineer, and what do people most often get wrong?”

What are the latest JavaScript (ES2023–ES2025) features worth knowing?

AdvancedJavaScript
  • Non-mutating array methods: toSorted(), toReversed(), toSpliced(), with()
  • findLast() / findLastIndex()
  • Object.groupBy() / Map.groupBy() for grouping arrays
  • Promise.withResolvers() to create a promise with its resolve/reject functions exposed
  • New Set methods: union, intersection, difference, isSubsetOf
  • Iterator helpers: .map(), .filter() and .take() on iterators
  • RegExp v flag, and import attributes for JSON modules
JavaScript
const sorted = prices.toSorted((a, b) => a - b);        // original untouched
const byDept = Object.groupBy(employees, e => e.dept);
const common = new Set([1, 2, 3]).intersection(new Set([2, 3, 4]));   // Set {2, 3}

JavaScript Coding Interview Questions (Programs with Code)

12 questions

Hands-on JavaScript programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.

How interviewers ask it“Can you reverse a string in JavaScript? Then walk me through the edge cases you would test.”

How do you reverse a string in JavaScript?

CodingJavaScript
Quick answerSpread the string into an array of characters, reverse it and join it back. Spreading (rather than split("")) keeps emojis and other surrogate pairs intact.
JavaScript
const reverse = (s) => [...s].reverse().join("");
reverse("hello");   // "olleh"
reverse("hi👋");    // "👋ih"  (split("") would break the emoji)

// Without built-ins
function reverseManual(s) {
  let out = "";
  for (let i = s.length - 1; i >= 0; i--) out += s[i];
  return out;
}

How interviewers ask it“Coding-round task — remove duplicates from an array in JavaScript. Explain your approach before you write the code.”

How do you remove duplicates from an array?

CodingJavaScript
Quick answerA Set keeps only unique values; spread it back into an array — O(n). For arrays of objects, de-duplicate by a key with a Map.
JavaScript
const unique = [...new Set([3, 1, 3, 2, 1])];       // [3, 1, 2]

const users = [{ id: 1, n: "A" }, { id: 2, n: "B" }, { id: 1, n: "A2" }];
const uniqueById = [...new Map(users.map(u => [u.id, u])).values()];  // last one wins per id

How interviewers ask it“Coding-round task — flatten a nested array in JavaScript. Explain your approach before you write the code.”

How do you flatten a nested array?

CodingJavaScript
Quick answerUse arr.flat(Infinity) in modern JavaScript. In interviews, also show a recursive version with an optional depth.
JavaScript
[1, [2, [3, [4]]]].flat(Infinity);     // [1, 2, 3, 4]

function flatten(arr, depth = Infinity) {
  return arr.reduce((acc, item) =>
    Array.isArray(item) && depth > 0 ? acc.concat(flatten(item, depth - 1)) : acc.concat(item), []);
}

How interviewers ask it“Can you group an array of objects by a property in JavaScript? Then walk me through the edge cases you would test.”

How do you group an array of objects by a property?

CodingJavaScript
Quick answerUse Object.groupBy (ES2024) or reduce for older environments.
JavaScript
const orders = [{ id: 1, status: "paid" }, { id: 2, status: "pending" }, { id: 3, status: "paid" }];

const grouped = Object.groupBy(orders, o => o.status);
// { paid: [{id:1}, {id:3}], pending: [{id:2}] }

const grouped2 = orders.reduce((acc, o) => {
  (acc[o.status] ??= []).push(o);
  return acc;
}, {});
CodingJavaScript
Quick answerCache results by their arguments so repeated calls with the same input return instantly — useful for expensive pure functions.
JavaScript
function memoize(fn, keyFn = (...args) => JSON.stringify(args)) {
  const cache = new Map();
  return function (...args) {
    const key = keyFn(...args);
    if (!cache.has(key)) cache.set(key, fn.apply(this, args));
    return cache.get(key);
  };
}
const fib = memoize(n => (n < 2 ? n : fib(n - 1) + fib(n - 2)));
fib(80);   // fast
CodingJavaScript
Quick answerCompare primitives directly; for objects and arrays, compare their key sets and recurse.
JavaScript
function deepEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
  if (Array.isArray(a) !== Array.isArray(b)) return false;
  const ka = Object.keys(a), kb = Object.keys(b);
  if (ka.length !== kb.length) return false;
  return ka.every(k => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
}
deepEqual({ x: [1, { y: 2 }] }, { x: [1, { y: 2 }] });   // true
CodingJavaScript
Quick answerCount occurrences with a Map in one pass, then pick the maximum — O(n).
JavaScript
function mostFrequent(arr) {
  const counts = new Map();
  let best = null, max = 0;
  for (const x of arr) {
    const c = (counts.get(x) ?? 0) + 1;
    counts.set(x, c);
    if (c > max) { max = c; best = x; }
  }
  return { value: best, count: max };
}
mostFrequent(["js", "py", "js", "go", "js"]);   // { value: "js", count: 3 }
CodingJavaScript
Quick answerStore listeners per event name; support on, off, once and emit.
JavaScript
class EventEmitter {
  #events = new Map();
  on(name, fn) { (this.#events.get(name) ?? this.#events.set(name, []).get(name)).push(fn); return () => this.off(name, fn); }
  off(name, fn) { this.#events.set(name, (this.#events.get(name) ?? []).filter(f => f !== fn && f.orig !== fn)); }
  once(name, fn) { const w = (...a) => { this.off(name, w); fn(...a); }; w.orig = fn; return this.on(name, w); }
  emit(name, ...args) { [...(this.#events.get(name) ?? [])].forEach(fn => fn(...args)); }
}
const bus = new EventEmitter();
const unsubscribe = bus.on("order", o => console.log("New order", o.id));
bus.emit("order", { id: 7 });
unsubscribe();
CodingJavaScript
Quick answerRun at most N async tasks at a time — for example to avoid flooding an API.
JavaScript
async function asyncPool(limit, items, worker) {
  const results = new Array(items.length);
  let next = 0;
  async function run() {
    while (next < items.length) {
      const i = next++;
      results[i] = await worker(items[i], i);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run));
  return results;
}
const pages = await asyncPool(3, urls, (u) => fetch(u).then(r => r.text()));
CodingJavaScript
Quick answerRetry a failing async operation with increasing delays and give up after N attempts.
JavaScript
const sleep = (ms) => new Promise(r => setTimeout(r, ms));

async function retry(fn, { retries = 3, base = 300 } = {}) {
  for (let attempt = 0; ; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt >= retries) throw err;
      await sleep(base * 2 ** attempt + Math.random() * 100);   // backoff + jitter
    }
  }
}
await retry(() => fetch("/api/report").then(r => { if (!r.ok) throw new Error(r.status); return r.json(); }));

How interviewers ask it“Coding-round task — chunk an array into groups of size n in JavaScript. Explain your approach before you write the code.”

How do you chunk an array into groups of size n?

CodingJavaScript
Quick answerSlice the array in steps of size.
JavaScript
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size));

chunk([1, 2, 3, 4, 5], 2);   // [[1, 2], [3, 4], [5]]
CodingJavaScript
Quick answerNormalise both strings, count character frequencies and compare — O(n), better than sorting (O(n log n)).
JavaScript
function isAnagram(a, b) {
  const clean = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
  a = clean(a); b = clean(b);
  if (a.length !== b.length) return false;
  const count = {};
  for (const ch of a) count[ch] = (count[ch] ?? 0) + 1;
  for (const ch of b) { if (!count[ch]) return false; count[ch]--; }
  return true;
}
isAnagram("Listen", "Silent");   // true

JavaScript Scenario Questions for 5+ Years Experience

6 questions

Real-world, scenario-based JavaScript questions with detailed answers, interview tips, common mistakes and follow-ups — the kind senior interviewers actually ask.

ExperiencedJavaScript
Quick answerThe event loop runs one macrotask (script, setTimeout, I/O, UI event) at a time. After each one, it drains the entire microtask queue (promise callbacks, queueMicrotask, MutationObserver) before rendering or starting the next macrotask.
JavaScript
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
queueMicrotask(() => console.log("4"));
(async () => {
  console.log("5");
  await null;
  console.log("6");
})();
console.log("7");
// Output: 1 5 7 3 4 6 2

Synchronous code runs first (1, 5, 7). Then the microtasks run in the order they were queued (3, 4, then the continuation after await: 6). The timer is a macrotask, so it runs last (2).

💡 Interview tip: Narrate each queue out loud as you trace the code — the reasoning matters more than the final answer.
Likely follow-up questions
  • Can microtasks starve rendering? (Yes — a microtask that keeps queuing microtasks blocks the page forever.)
ExperiencedJavaScript
Quick answerPromise.all resolves with an array of results in input order once every promise fulfils, and rejects as soon as any one rejects. It must also accept non-promise values and an empty input.
JavaScript
function promiseAll(iterable) {
  return new Promise((resolve, reject) => {
    const items = Array.from(iterable);
    const results = new Array(items.length);
    let remaining = items.length;
    if (remaining === 0) return resolve(results);

    items.forEach((item, i) => {
      Promise.resolve(item).then((value) => {
        results[i] = value;              // keep input order
        if (--remaining === 0) resolve(results);
      }, reject);                        // first rejection wins
    });
  });
}

promiseAll([1, Promise.resolve(2), new Promise((r) => setTimeout(() => r(3), 10))])
  .then(console.log); // [1, 2, 3]
Likely follow-up questions
  • How do Promise.allSettled, Promise.any and Promise.race differ?
ExperiencedJavaScript
  • Debounce runs the function only after calls have stopped for wait ms — search-as-you-type, auto-save, resize handlers.
  • Throttle runs it at most once per wait ms while calls keep coming — scroll tracking, rate-limited API calls.
JavaScript
function debounce(fn, wait = 300) {
  let t;
  return function (...args) {
    clearTimeout(t);
    t = setTimeout(() => fn.apply(this, args), wait);
  };
}

function throttle(fn, wait = 200) {
  let last = 0, timer = null;
  return function (...args) {
    const now = Date.now();
    const remaining = wait - (now - last);
    if (remaining <= 0) {
      last = now;
      fn.apply(this, args);
    } else if (!timer) {
      timer = setTimeout(() => {          // trailing call
        last = Date.now(); timer = null; fn.apply(this, args);
      }, remaining);
    }
  };
}

input.addEventListener("input", debounce((e) => search(e.target.value), 250));
Common mistakes
  • Using an arrow function for the returned wrapper and losing the caller's this.
ExperiencedJavaScript
Quick answerJavaScript is garbage-collected, but anything still reachable is never freed. Common leaks:
  • Event listeners, intervals and subscriptions that are never removed (for example, when a component unmounts)
  • Closures that hold references to large objects or detached DOM nodes
  • Unbounded caches and Maps keyed by objects (use WeakMap or an LRU cache)
  • Accidental globals

Finding them: in Chrome DevTools → Memory, take heap snapshots before and after repeating an action, compare them, and look for growing object counts and "Detached" DOM nodes. In Node.js, use --inspect with heap snapshots or --heapsnapshot-near-heap-limit.

JavaScript
// React-style cleanup prevents the classic listener leak
useEffect(() => {
  const onResize = () => setWidth(window.innerWidth);
  window.addEventListener("resize", onResize);
  const id = setInterval(poll, 5000);
  return () => {                      // runs on unmount
    window.removeEventListener("resize", onResize);
    clearInterval(id);
  };
}, []);

const meta = new WeakMap();           // entries are dropped when the key object is collected
ExperiencedJavaScript
Quick answerthis is decided by how a function is called, checked in this order of precedence:
  1. new binding: new Foo() → the newly created object
  2. Explicit binding: fn.call(obj), fn.apply(obj), fn.bind(obj) → obj
  3. Implicit binding: obj.method() → obj
  4. Default binding: a plain fn() → undefined in strict mode or modules (the global object otherwise)

Arrow functions have no this of their own; they use the this of the enclosing scope at the point they are defined, and call/bind can't change it.

JavaScript
const counter = {
  count: 0,
  incLater() {
    setTimeout(function () { this.count++; }, 0);  // `this` is not counter
    setTimeout(() => { this.count++; }, 0);         // arrow: `this` is counter
  },
};

const { incLater } = counter;
incLater(); // implicit binding lost: `this` is undefined in strict mode
ExperiencedJavaScript
ES Modules (ESM)CommonJS (CJS)
Syntaximport / exportrequire() / module.exports
LoadingStatic, async-capable; top-level awaitSynchronous, at runtime
Tree-shakingYes (static analysis)Limited
BindingsLive bindingsCopied values
Default inBrowsers, Deno, Bun, modern Node.jsOlder Node.js packages

ESM is the standard. Recent Node.js versions can even require() ESM modules synchronously (as long as they don't use top-level await), which eases migration. Interviewers check that you understand tree-shaking, dual packages and "type": "module" in package.json.

JavaScript
// math.mjs
export const add = (a, b) => a + b;
export default function mul(a, b) { return a * b; }

// app.mjs
import mul, { add } from "./math.mjs";
const config = await import("./config.mjs");   // dynamic import, code-splitting

Practise with the free JavaScript quiz

Multiple-choice questions with instant feedback. Takes about 10 minutes and shows exactly which concepts to revise.

Start the JavaScript quiz →

JavaScript interview FAQ

What JavaScript questions are asked for 5 years of experience?
Expect event loop and async ordering puzzles, closures and memory leaks, prototype chain and classes, this binding rules, writing polyfills (bind, Promise.all, debounce), performance (rendering, long tasks), module systems (ESM vs CommonJS), error handling in async code and browser APIs.
What are the top JavaScript interview questions for freshers?
Data types, var vs let vs const, hoisting, == vs ===, closures, the this keyword, arrow functions, callbacks vs promises vs async/await, array methods (map, filter, reduce), the spread and rest operators, and event bubbling and delegation.
How do I prepare for a JavaScript interview in 2026?
Master the language core (scope, closures, this, prototypes, the event loop), practise writing polyfills and async utilities by hand, revise modern syntax (optional chaining, ES modules, new array methods), and be ready to debug output-based questions step by step.
What JavaScript questions are asked for freshers?
Data types, var vs let vs const, hoisting, == vs ===, truthy and falsy values, null vs undefined, functions and arrow functions, scope, array methods (map, filter, reduce), objects and JSON, DOM basics and events, and simple programs like reversing a string or removing duplicates.
What JavaScript topics are most important for experienced developers?
Closures, the event loop and microtasks, promises and async/await error handling, prototypal inheritance, this binding, call/apply/bind, memory leaks, performance (reflow, long tasks), security (XSS, CSRF, CSP, CORS), module systems and writing polyfills such as debounce, throttle and Promise.all.
Is JavaScript enough to get a job in 2026?
JavaScript plus one framework (React is the most in demand), TypeScript, Git, basic Node.js and REST APIs is enough for most frontend and junior full-stack roles. Strong fundamentals matter more than knowing many libraries.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.