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
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
60 shown
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.
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.
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.
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 3for (let j = 0; j < 3; j++) setTimeout(() =>console.log(j)); // 0 1 2 (new binding per iteration)
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 hoistedfunctiongreet() { console.log("hi"); }
console.log(a); // undefinedvar a = 1;
console.log(b); // ReferenceError (TDZ)let b = 2;
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.
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
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.
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.
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"}.`;
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.
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");
});
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
functioncreateCounter() {
let count = 0; // private — not reachable from outsidereturn {
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.)
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 prototypeObject.getPrototypeOf(dog) === animal; // true
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).
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 secondconst a = awaitgetUser(); const b = awaitgetOrders(); const c = awaitgetCart();
// Parallel: ~1 secondconst [user, orders, cart] = awaitPromise.all([getUser(), getOrders(), getCart()]);
// Partial results are acceptableconst results = awaitPromise.allSettled(urls.map(u =>fetch(u)));
const ok = results.filter(r => r.status === "fulfilled").map(r => r.value);
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.
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
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 = newMap();
visits.set(userObj, 3);
const unique = [...newSet([1, 2, 2, 3])]; // [1, 2, 3]const meta = newWeakMap();
meta.set(domNode, { tooltip: "Save" }); // freed with the node
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
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.
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"asyncfunction* pages(url) { // async generator for paginated APIsfor (let next = url; next; ) {
const res = await (awaitfetch(next)).json();
yield res.items; next = res.nextUrl;
}
}
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.
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
asyncfunctiongetJSON(url, ms = 5000) {
const res = awaitfetch(url, { signal: AbortSignal.timeout(ms), headers: { Accept: "application/json" } });
if (!res.ok) thrownewError(`Request failed: ${res.status}`);
return res.json();
}
const controller = newAbortController();
fetch("/api/search?q=java", { signal: controller.signal });
controller.abort(); // cancels it (e.g. when a new search starts)
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.
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).
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.
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
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.
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).
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.
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.
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.
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.
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.
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?”
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 untouchedconst byDept = Object.groupBy(employees, e => e.dept);
const common = newSet([1, 2, 3]).intersection(newSet([2, 3, 4])); // Set {2, 3}
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
constreverse = (s) => [...s].reverse().join("");
reverse("hello"); // "olleh"reverse("hi👋"); // "👋ih" (split("") would break the emoji)// Without built-insfunctionreverseManual(s) {
let out = "";
for (let i = s.length - 1; i >= 0; i--) out += s[i];
return out;
}
Quick answerNormalise both strings, count character frequencies and compare — O(n), better than sorting (O(n log n)).
JavaScript
functionisAnagram(a, b) {
constclean = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
a = clean(a); b = clean(b);
if (a.length !== b.length) returnfalse;
const count = {};
for (const ch of a) count[ch] = (count[ch] ?? 0) + 1;
for (const ch of b) { if (!count[ch]) returnfalse; count[ch]--; }
returntrue;
}
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.
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.
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.)
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.
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 leakuseEffect(() => {
constonResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", onResize);
const id = setInterval(poll, 5000);
return() => { // runs on unmountwindow.removeEventListener("resize", onResize);
clearInterval(id);
};
}, []);
const meta = newWeakMap(); // entries are dropped when the key object is collected
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.mjsexportconstadd = (a, b) => a + b;
exportdefaultfunctionmul(a, b) { return a * b; }
// app.mjsimport mul, { add } from"./math.mjs";
const config = awaitimport("./config.mjs"); // dynamic import, code-splitting
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.