
These are the JavaScript interview questions I’d study if I had a frontend loop next month: 300+ of them, grouped by topic and ordered from basic to senior. Every question has an answer, most have code you can paste into a console, and most link to a FrontendLead problem or deep dive so you can practice instead of just reading.
JavaScript shows up in every frontend interview. Sometimes it’s a trivia round (“what does this log?”), sometimes it’s hidden inside a coding round (“implement debounce”), and sometimes it’s the reason a React bug happens. Interviewers aren’t checking whether you memorized the spec. They’re checking whether you can predict what code does and explain why. The answers follow the MDN JavaScript reference, and the outputs shown were checked by running the code.
What to Expect
- 11 sections, from types and coercion to async internals, modern ES2015-ES2025 features, the DOM, security, and senior-level questions.
- Direct answers first, then the detail that turns an okay answer into a strong one: code, trade-offs, and pitfalls.
- A section of “what does this log?” output questions, the format many phone screens use.
- JavaScript coding interview questions with full solutions (debounce, throttle,
Promise.all, deep clone, curry, and more), plus the full list of 75 coding questions to practice in the browser.
Short on time? How to Use This List at the end has a study order by level.
Jump to a section
- JavaScript Fundamentals: Types, Coercion, and Scope (Q1-30)
- Functions, Closures, and this (Q31-60)
- Objects, Prototypes, and Classes (Q61-90)
- Arrays, Strings, and Collections (Q91-120)
- Asynchronous JavaScript and the Event Loop (Q121-155)
- Modern JavaScript: ES2015 to ES2025 (Q156-180)
- DOM, Events, and Browser APIs (Q181-210)
- Memory, Performance, and Security (Q211-235)
- What Does This Code Log? Output Questions (Q236-255)
- JavaScript Coding Interview Questions (Q256-290)
- Advanced JavaScript Interview Questions for Experienced Developers (Q291-310)
JavaScript Fundamentals: Types, Coercion, and Scope

Find in-depth explanations and practice here: JavaScript Fundamentals ->
Fundamentals questions look easy, which is why they filter so many people. Interviewers use them to check whether you can predict what the engine does, not whether you can recite definitions.
1. What are the data types in JavaScript?
There are eight: seven primitives (string, number, bigint, boolean, undefined, null, symbol) and object. Arrays, functions, dates, maps, and regular expressions are all objects.
typeof "hi"; // "string"
typeof 42; // "number"
typeof 42n; // "bigint"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof Symbol(); // "symbol"
typeof null; // "object" (historical bug, see Q7)
typeof {}; // "object"
typeof []; // "object"
typeof (() => {}); // "function" (still an object)
2. What is the difference between primitive and reference types?
Primitives are immutable values compared by value. Objects are mutable and compared by reference: two variables can point to the same object, and two objects with identical contents are not equal.
let a = "x";
let b = a;
b = "y";
console.log(a); // "x" (primitives are copied)
const o1 = { n: 1 };
const o2 = o1;
o2.n = 2;
console.log(o1.n); // 2 (same object)
console.log({ n: 1 } === { n: 1 }); // false (different references)
Strictly speaking, JavaScript always passes arguments by value. For objects, the value being copied is the reference. That’s why reassigning a parameter inside a function doesn’t affect the caller, but mutating it does.
3. What is the difference between == and ===?
=== (strict equality) compares type and value with no conversion. == (loose equality) converts the operands to a common type first, following rules that are easy to get wrong.
0 == ""; // true ("" becomes 0)
0 === ""; // false
null == undefined; // true (special case)
null === undefined; // false
"1" == 1; // true
[1] == 1; // true ([1] -> "1" -> 1)
NaN === NaN; // false
Object.is(NaN, NaN); // true
Object.is(0, -0); // false
Use === by default. The one common exception is value == null, which checks for both null and undefined in one go.
4. What is type coercion?
Coercion is converting a value from one type to another. It’s explicit when you call Number(x), String(x), or Boolean(x), and implicit when an operator does it for you (==, +, if (x), template literals).
"5" * 2; // 10 (* only works on numbers)
"5" + 2; // "52" (+ prefers strings if either side is a string)
true + 1; // 2
[] + {}; // "[object Object]"
`${[1, 2]}`; // "1,2"
Deep dive: Type coercion in JavaScript
5. What are truthy and falsy values?
Falsy values become false in a boolean context. There are exactly eight: false, 0, -0, 0n, "", null, undefined, and NaN. Everything else is truthy, including "0", "false", [], and {}.
This is a classic bug source: if (items.length) works, but if (count) treats a legitimate 0 as “missing”.
6. What is the difference between null, undefined, and undeclared?
| Meaning | typeof | |
|---|---|---|
undefined |
Declared but not assigned, or a missing property or argument | "undefined" |
null |
An intentional “no value”, set by you | "object" |
| Undeclared | Never declared; reading it throws ReferenceError |
"undefined" (typeof doesn’t throw) |
Deep dive: null, undefined, and undeclared variables
7. Why does typeof null return “object”?
It’s a bug from the first version of JavaScript. Values were stored with a type tag, and the tag for objects was 0. null was represented as the null pointer (all zeros), so it read as an object. Fixing it would break existing websites, so it stayed. To check for null, use value === null.
8. How do you reliably check the type of a value?
Use the right tool for each case: typeof for primitives and functions, Array.isArray for arrays, === null for null, instanceof for class instances (same realm only), and Object.prototype.toString when you need a precise tag.
const typeOf = (v) => Object.prototype.toString.call(v).slice(8, -1).toLowerCase();
typeOf([]); // "array"
typeOf(null); // "null"
typeOf(new Date()); // "date"
typeOf(/x/); // "regexp"
typeOf(new Map()); // "map"
Practice: Precise Type Of
9. What is NaN, and how do you check for it?
NaN (“not a number”) is a number value that represents a failed numeric operation, like Number("abc") or 0 / 0. It’s the only value not equal to itself. Use Number.isNaN(x). The global isNaN(x) converts its argument first, so isNaN("abc") is true even though "abc" isn’t NaN.
Number.isNaN(NaN); // true
Number.isNaN("abc"); // false
isNaN("abc"); // true (coerced to NaN first)
10. Why is 0.1 + 0.2 !== 0.3?
JavaScript numbers are 64-bit IEEE 754 floating-point values. 0.1 and 0.2 can’t be represented exactly in binary, so their sum is 0.30000000000000004. Compare with a tolerance, or work in integers (cents instead of dollars) for money.
0.1 + 0.2; // 0.30000000000000004
Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON; // true
11. What is Number.MAX_SAFE_INTEGER, and when do you need BigInt?
Number.MAX_SAFE_INTEGER is 253 – 1 (9007199254740991). Above it, integers lose precision: 2 ** 53 === 2 ** 53 + 1 is true. Use BigInt (123n) for large IDs, cryptography, or exact integer math. You can’t mix BigInt and Number in arithmetic without converting explicitly, and JSON.stringify throws on BigInt.
12. What is the difference between var, let, and const?
| Scope | Hoisted | Reassign | Redeclare | |
|---|---|---|---|---|
var |
Function | Yes, initialized to undefined |
Yes | Yes |
let |
Block | Yes, but in the TDZ until declared | Yes | No |
const |
Block | Yes, but in the TDZ until declared | No | No |
Default to const, use let when you need to reassign, and avoid var. Top-level var in a classic script also becomes a property of window; let and const don’t.
Deep dive: let, var, and const differences
13. What is hoisting?
Before code runs, the engine registers every declaration in its scope. Function declarations are fully hoisted (you can call them before the line they’re defined on). var declarations are hoisted and set to undefined. let, const, and class are hoisted but not initialized.
console.log(a); // undefined
var a = 1;
greet(); // "hi" (function declarations are hoisted with their body)
function greet() { console.log("hi"); }
Deep dive: Hoisting in JavaScript
14. What is the temporal dead zone (TDZ)?
The TDZ is the time between entering a scope and reaching a let, const, or class declaration. Accessing the variable during that time throws a ReferenceError. It exists so that reading a variable before its declaration is an error instead of a silent undefined.
{
// console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 1;
console.log(x); // 1
}
15. Does const make a value immutable?
No. const prevents reassigning the binding, not mutating the value. You can still push into a const array or change a property of a const object. For shallow immutability, use Object.freeze; for deep immutability, freeze recursively or use immutable update patterns.
const list = [1];
list.push(2); // fine
// list = []; // TypeError: Assignment to constant variable
16. What is scope, and what kinds of scope exist?
Scope decides where a variable is visible. JavaScript has global scope, module scope (each ES module has its own top level), function scope, and block scope (anything in {} for let, const, and class).
17. What is lexical scope?
Lexical (static) scope means a function’s access to variables is decided by where it’s written in the source, not where it’s called from. That’s what makes closures possible.
const name = "outer";
function show() { console.log(name); }
function run() {
const name = "inner";
show();
}
run(); // "outer" (show sees the scope it was defined in)
Deep dive: Lexical scope in JavaScript
18. What is the scope chain?
When code reads a variable, the engine looks in the current scope, then the enclosing scope, and so on up to the global scope. The first match wins. If nothing matches, it throws a ReferenceError (or, in sloppy mode, an assignment creates an accidental global).
19. What is variable shadowing?
Shadowing happens when an inner scope declares a variable with the same name as an outer one. The inner one hides the outer one inside that scope. It’s legal, but it often hides bugs, which is why linters warn about it (no-shadow).
20. Why are global variables a problem, and what is globalThis?
Globals can be overwritten by any script, collide with third-party code, make dependencies invisible, and stay in memory for the lifetime of the page. Prefer modules, which have their own scope. globalThis is the standard way to reach the global object in any environment (window in browsers, global in Node, self in workers).
21. What does “use strict” do?
Strict mode turns silent mistakes into errors and removes some confusing features: assigning to an undeclared variable throws, this is undefined in plain function calls instead of the global object, duplicate parameter names are a syntax error, writing to read-only properties throws, and with is banned. ES modules and class bodies are strict automatically.
Deep dive: Using “use strict” in JavaScript
22. What is the difference between a function declaration and a function expression?
A declaration (function add() {}) is hoisted with its body, so you can call it before it appears. An expression (const add = function () {} or an arrow function) follows the variable’s rules: with const it’s in the TDZ until that line runs.
Deep dive: Function declarations vs expressions
23. What is an IIFE, and is it still useful?
An immediately invoked function expression runs as soon as it’s defined: (function () { ... })(). Before modules and block scope, IIFEs were the way to create private scope and avoid globals. Today modules cover most of that, but an async IIFE is still handy to use await in a script that isn’t a module.
(async () => {
const res = await Promise.resolve("done");
console.log(res); // "done"
})();
24. How do you convert a string to a number?
Number(str) and unary +str convert the whole string and return NaN if any part is invalid. parseInt(str, 10) and parseFloat(str) read from the start and stop at the first invalid character. Always pass the radix to parseInt.
Number("42px"); // NaN
parseInt("42px", 10); // 42
Number(""); // 0 (surprising)
parseInt("", 10); // NaN
["1", "2", "3"].map(parseInt); // [1, NaN, NaN] (map passes the index as the radix)
25. What do 1 + “2” + 3 and 1 + 2 + “3” return?
+ evaluates left to right and switches to string concatenation as soon as one side is a string.
1 + "2" + 3; // "123"
1 + 2 + "3"; // "33"
"3" - 1; // 2 (minus only works on numbers)
26. How do the logical operators && and || work?
They short-circuit and return one of their operands, not necessarily a boolean. a || b returns a if it’s truthy, otherwise b. a && b returns a if it’s falsy, otherwise b.
"" || "default"; // "default"
"x" && "y"; // "y"
0 && expensive(); // 0 (expensive is never called)
27. What is the difference between ?? and ||?
The nullish coalescing operator ?? falls back only when the left side is null or undefined. || falls back on any falsy value, which wrongly replaces valid values like 0 and "".
const volume = 0;
volume || 50; // 50 (bug: 0 is a valid volume)
volume ?? 50; // 0
28. What is optional chaining?
a?.b returns undefined instead of throwing when a is null or undefined. It also works for calls (fn?.()) and dynamic keys (obj?.[key]). Don’t use it everywhere: if a value should never be missing, a crash is more useful than silently getting undefined.
const user = { profile: null };
user.profile?.name; // undefined
user.settings?.theme ?? "light"; // "light"
29. Is JavaScript compiled or interpreted?
Both. Modern engines (V8, SpiderMonkey, JavaScriptCore) parse the source, start running it in an interpreter, and compile hot functions to optimized machine code with a just-in-time (JIT) compiler. If an assumption breaks (for example, a function that always got numbers suddenly gets a string), the engine de-optimizes that code.
30. Is JavaScript single-threaded?
Your JavaScript runs on one main thread with one call stack, so two pieces of your code never run at the same time on it. The browser itself is multi-threaded: networking, timers, and parsing happen elsewhere, and their callbacks are queued back to your thread through the event loop. For real parallel JavaScript, you use Web Workers. Section 5 covers the event loop in depth.
Deep dive: Synchronous vs asynchronous functions
Functions, Closures, and this

Find in-depth explanations and practice here: Closures in JavaScript ->
Closures and this are the two topics that come up in almost every JavaScript interview. They’re also behind most coding questions: debounce, memoize, curry, and once are all closures.
31. What is a closure?
A closure is a function together with the variables from the scope it was created in. The inner function keeps access to those variables even after the outer function has returned.
function counter() {
let count = 0;
return () => ++count;
}
const next = counter();
next(); // 1
next(); // 2 (count survives between calls)
The variables are captured by reference, not copied. If the outer variable changes later, the closure sees the new value.
32. What are closures used for in practice?
- Private state: variables nobody outside can touch (the counter above).
- Function factories:
makeMultiplier(2)returns a function that remembers 2. - Caching: memoize keeps a cache in a closure.
- Timing utilities: debounce and throttle keep a timer id in a closure.
- Event handlers and React hooks: every handler closes over the props and state of its render.
33. Why does this loop log 3, 3, 3, and how do you fix it?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 3, 3, 3
var is function-scoped, so there’s one i shared by all three callbacks. By the time the timers fire, the loop has finished and i is 3. The fix is let, which creates a new binding for every iteration, so the output becomes 0, 1, 2. Before let, people wrapped the body in an IIFE that took i as a parameter.
34. Can closures cause memory leaks?
Yes, indirectly. A closure keeps its captured variables alive for as long as the closure itself is reachable. A long-lived closure (an event listener that’s never removed, a callback stored in a global cache, an interval that’s never cleared) can keep large objects or detached DOM nodes in memory. The fix is to remove listeners, clear timers, and avoid capturing more than you need.
Deep dive: Identifying memory leaks in browser applications
35. What does it mean that functions are first-class?
Functions are values. You can store them in variables, pass them as arguments, return them from other functions, and attach properties to them. Callbacks, higher-order functions, and closures all depend on this.
36. What is a higher-order function?
A function that takes a function as an argument, returns a function, or both. map, filter, reduce, addEventListener, debounce, and memoize are all higher-order functions.
Deep dive: Higher-order functions with examples
37. What is a pure function?
A pure function returns the same output for the same input and has no side effects: it doesn’t mutate arguments, touch the DOM, make requests, or read changing global state. Pure functions are easy to test, cache, and reason about, which is why reducers and React render functions are expected to be pure.
Deep dive: Fundamentals of functional programming
38. What is the difference between arrow functions and regular functions?
| Regular function | Arrow function | |
|---|---|---|
this |
Set by how it’s called | Inherited from the enclosing scope |
arguments |
Yes | No (use rest parameters) |
Callable with new |
Yes | No (TypeError) |
prototype property |
Yes | No |
| Hoisted (declaration form) | Yes | No (it’s always an expression) |
39. When should you not use an arrow function?
Don’t use one when you need a dynamic this: object methods that read this, prototype methods, constructors, and DOM handlers where you want this to be the element. In those cases, an arrow function captures the outer this (often undefined in a module) instead.
const user = {
name: "Ada",
arrow: () => this?.name, // this is the module's this (undefined)
method() { return this.name; },
};
user.arrow(); // undefined
user.method(); // "Ada"
40. How does this work in JavaScript?
this is decided by how a function is called, not where it’s defined (except for arrow functions). Check these rules in order:
new:new Foo()setsthisto the new object.- Explicit:
call,apply, orbindsetthisto the first argument. - Method call:
obj.method()setsthistoobj. - Plain call:
fn()setsthistoundefinedin strict mode, or the global object in sloppy mode.
Arrow functions skip all four rules and use the this of the scope they were defined in.
Deep dive: Understanding this in JavaScript
41. Why do methods lose this when passed as callbacks?
Passing obj.method passes the function alone, without the object. When it’s called later as a plain function, rule 4 applies and this is undefined.
class Timer {
seconds = 0;
tick() { this.seconds++; }
}
const t = new Timer();
const tick = t.tick;
// tick(); // TypeError: Cannot read properties of undefined
const bound = t.tick.bind(t);
bound();
console.log(t.seconds); // 1
Fixes: bind, wrap the call in an arrow function (() => t.tick()), or define the method as an arrow-function class field (tick = () => { ... }).
42. What is the difference between call, apply, and bind?
| Method | Calls now? | Arguments |
|---|---|---|
fn.call(ctx, a, b) |
Yes | One by one |
fn.apply(ctx, [a, b]) |
Yes | As an array |
fn.bind(ctx, a) |
No, returns a new function | Pre-filled (partial application) |
With spread syntax, apply is rarely needed: fn.call(ctx, ...args) does the same.
Deep dive: call vs apply in JavaScript
43. How would you implement Function.prototype.bind?
Function.prototype.myBind = function (ctx, ...preset) {
const fn = this;
return function bound(...args) {
// When called with new, ignore ctx and construct normally.
if (new.target) return new fn(...preset, ...args);
return fn.apply(ctx, [...preset, ...args]);
};
};
function greet(greeting, mark) { return `${greeting}, ${this.name}${mark}`; }
greet.myBind({ name: "Ada" }, "Hi")("!"); // "Hi, Ada!"
Practice: Custom “this” Methods
44. Can you change this on a bound function?
No. Calling bind, call, or apply on an already bound function can add arguments, but this stays the first bound value. The only exception is new: constructing a bound function ignores the bound this.
45. What are default and rest parameters?
Default parameters apply when an argument is undefined (not when it’s null). Rest parameters collect the remaining arguments into a real array.
function tag(label = "none", ...items) {
return `${label}: ${items.join(", ")}`;
}
tag(undefined, "a", "b"); // "none: a, b"
tag(null); // "null: "
46. What is the arguments object, and why prefer rest parameters?
arguments is an array-like object with every argument passed to a regular function. It’s not a real array (no map), it doesn’t exist in arrow functions, and in sloppy mode it’s linked to the named parameters in confusing ways. Rest parameters (...args) are a real array and make the signature explicit.
47. What is currying?
Currying turns a function of N arguments into a chain of functions that each take some of the arguments until all N are supplied: add(1)(2)(3) instead of add(1, 2, 3).
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...more) => curried.apply(this, [...args, ...more]);
};
}
const add3 = curry((a, b, c) => a + b + c);
add3(1)(2)(3); // 6
add3(1, 2)(3); // 6
Practice: Curry Function. Deep dive: Currying in JavaScript
48. What is the difference between currying and partial application?
Partial application fixes some arguments once and returns a function that takes the rest (fn.bind(null, 1)). Currying always produces a chain of single-step functions until every argument is provided. Curried functions make partial application easy, but they’re not the same thing.
49. What are compose and pipe?
Both combine functions into one. compose(f, g)(x) runs right to left (f(g(x))); pipe(f, g)(x) runs left to right (g(f(x))), which usually reads more naturally.
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
pipe((n) => n + 1, (n) => n * 2)(3); // 8
compose((n) => n + 1, (n) => n * 2)(3); // 7
Practice: Compose Function
50. What is memoization, and how do you implement it?
Memoization caches a function’s results by its arguments so repeated calls return instantly. It only works for pure functions, and the cache key is the hard part: a JSON key breaks for functions and object identity, while a Map keyed by a single primitive argument is simple and fast.
function memoize(fn, key = (...args) => JSON.stringify(args)) {
const cache = new Map();
return function (...args) {
const k = key(...args);
if (!cache.has(k)) cache.set(k, fn.apply(this, args));
return cache.get(k);
};
}
const slowSquare = (n) => n * n;
const fastSquare = memoize(slowSquare);
fastSquare(9); // computed
fastSquare(9); // cached
In production, bound the cache (LRU or a WeakMap for object keys), or it grows forever. Practice: Memoize I and Memoize II
51. What is a callback, and what is callback hell?
A callback is a function you pass to another function to be called later, for example when a timer fires or a request finishes. Callback hell is deeply nested callbacks, where each async step lives inside the previous one, error handling is repeated at every level, and the flow is hard to follow. Promises and async/await flatten that structure.
52. What is recursion, and what are its risks in JavaScript?
A recursive function calls itself on a smaller input until it reaches a base case. The risk is the call stack: very deep recursion throws RangeError: Maximum call stack size exceeded. Proper tail calls are in the spec, but only Safari implements them, so convert deep recursion (like flattening huge trees) to a loop with an explicit stack.
Practice: Flatten arrays recursively and iteratively
53. What does the new keyword do?
- Creates a new empty object.
- Sets its prototype to the constructor’s
prototypeproperty. - Calls the constructor with
thisset to the new object. - Returns the new object, unless the constructor explicitly returns a different object.
function myNew(Ctor, ...args) {
const obj = Object.create(Ctor.prototype);
const result = Ctor.apply(obj, args);
return result !== null && (typeof result === "object" || typeof result === "function") ? result : obj;
}
54. How do you make a function run only once?
Keep a flag and the first result in a closure.
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}
const init = once(() => console.log("init"));
init(); // "init"
init(); // nothing
Practice: Run Only Once
55. How do you create private variables in JavaScript?
- Closures: variables in a factory function’s scope (Q31).
- Private class fields:
#countis enforced by the language and throws if accessed from outside. - WeakMap: keyed by the instance, used before
#fields existed.
class Counter {
#count = 0;
increment() { return ++this.#count; }
}
const c = new Counter();
c.increment(); // 1
// c.#count; // SyntaxError outside the class
56. What is the module pattern?
Before ES modules, the module pattern used an IIFE that returned an object of public functions while keeping everything else private in the closure. The “revealing module” variant defines everything privately and returns references to the parts you want public. ES modules replace it today: anything not exported is private to the file.
57. What is the difference between debounce and throttle?
Debounce waits until calls stop for N milliseconds, then runs once (search-as-you-type, resize end). Throttle runs at most once every N milliseconds while calls keep coming (scroll position, drag). Both are closures holding a timer. Full implementations are in the coding section (Q256 and Q257).
Deep dive: Debounce vs throttle
58. What are anonymous functions, and what’s the downside?
Anonymous functions have no name, like most inline callbacks. They’re convenient, but they show up as “anonymous” in stack traces, can’t call themselves recursively by name, and can’t be removed with removeEventListener unless you keep a reference. Name the function when it helps debugging.
Deep dive: Uses of anonymous functions
59. What do a function’s length and name properties return?
fn.length is the number of declared parameters before the first one with a default value or a rest parameter. Generic curry implementations rely on it. fn.name is the function’s name, inferred from the variable for anonymous functions assigned to one.
((a, b) => {}).length; // 2
((a, b = 1, c) => {}).length; // 1
((...args) => {}).length; // 0
const handler = () => {};
handler.name; // "handler"
60. What is the difference between a function and a method?
A method is a function stored as a property of an object and usually called through it (obj.method()), so this refers to the object. Technically any function can be called as a method or a plain function. What changes is this, which is why Q41’s “lost this” bug exists.
Objects, Prototypes, and Classes

Find in-depth explanations and practice here: Prototypal inheritance in JavaScript ->
Classes made JavaScript look like Java, but underneath it’s still prototypes. Interviewers ask about the prototype chain to see whether you know what class actually does.
61. What are the ways to create an object in JavaScript?
const a = { name: "Ada" }; // object literal
const b = Object.create(Object.prototype); // explicit prototype
const c = Object.create(null); // no prototype at all (a clean dictionary)
function User(name) { this.name = name; }
const d = new User("Ada"); // constructor function
class Account { constructor(id) { this.id = id; } }
const e = new Account(1); // class
const makeUser = (name) => ({ name }); // factory function
const f = makeUser("Ada");
62. What is a prototype?
Every object has an internal link ([[Prototype]]) to another object or null. When you read a property that the object doesn’t have, the engine looks it up on the prototype. That’s how arrays get map: the method lives once on Array.prototype, not on each array.
63. What is the prototype chain?
The chain of prototype links from an object up to null. Property lookup walks it until it finds the property or reaches the end (returning undefined). Writing a property, by contrast, creates it on the object itself (unless a setter exists up the chain).
const arr = [];
Object.getPrototypeOf(arr) === Array.prototype; // true
Object.getPrototypeOf(Array.prototype) === Object.prototype; // true
Object.getPrototypeOf(Object.prototype); // null
Deep dive: Harnessing prototypal inheritance
64. What is the difference between __proto__ and prototype?
prototype is a property on constructor functions and classes: the object that instances created with new will link to. __proto__ is a legacy accessor on every object that exposes its actual prototype link. So new User().__proto__ === User.prototype. Use Object.getPrototypeOf and Object.setPrototypeOf instead of __proto__.
65. What is the difference between prototypal and classical inheritance?
In classical inheritance (Java, C++), classes are blueprints and instances are copies of the blueprint. In prototypal inheritance, objects inherit directly from other objects through live links. If you add a method to a prototype later, every existing object linked to it gets the method immediately.
Deep dive: Classical inheritance in OOP
66. What is the difference between Object.create and new?
Object.create(proto) makes an object linked to proto without running any constructor. new Ctor() creates an object linked to Ctor.prototype and then runs Ctor to initialize it. Object.create(null) is useful for lookup tables that must not inherit keys like toString.
Deep dive: Object.create vs new
67. Are ES6 classes just syntactic sugar?
Mostly. A class still creates a constructor function and puts methods on its prototype. But there are real differences: classes must be called with new, their bodies are always strict, methods are non-enumerable, class declarations are in the TDZ until defined, and private fields (#x) have no prototype-based equivalent.
class Dog { bark() { return "woof"; } }
typeof Dog; // "function"
Object.getOwnPropertyNames(Dog.prototype); // ["constructor", "bark"]
// Dog(); // TypeError: Class constructor Dog cannot be invoked without 'new'
68. How does inheritance work with extends and super?
class B extends A links B.prototype to A.prototype (for methods) and B to A (for static methods). In a subclass constructor, you must call super() before using this, because the parent constructor is what creates the object.
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
speak() { return `${super.speak()}: woof`; }
}
new Dog("Rex").speak(); // "Rex makes a sound: woof"
69. What are static methods and fields?
Static members belong to the class itself, not instances: Date.now(), Array.from(), Number.isNaN(). Use them for factories (User.fromJSON(json)) and helpers that don’t need an instance. Inside a static method, this is the class.
70. How do private fields and methods work?
Members prefixed with # are only accessible inside the class body. Access from outside is a syntax error, not just a convention. You can check whether an object has a private field with #field in obj, which makes a safe brand check.
class Temperature {
#celsius = 0;
static isTemperature(obj) { return #celsius in obj; }
#validate(v) { if (v < -273.15) throw new RangeError("below absolute zero"); }
set celsius(v) { this.#validate(v); this.#celsius = v; }
get celsius() { return this.#celsius; }
}
Temperature.isTemperature(new Temperature()); // true
Temperature.isTemperature({}); // false
71. What are getters and setters?
Accessor properties that run a function when read (get) or written (set). Use them for computed values (fullName) or validation on write (the Temperature example above). Keep getters cheap and side-effect free; callers expect a property read to be fast.
72. What are property descriptors?
Every property has attributes: value, writable, enumerable (shows up in for...in and Object.keys), and configurable (can be deleted or redefined). Object.defineProperty defaults all three flags to false.
const obj = {};
Object.defineProperty(obj, "id", { value: 1 });
obj.id = 2; // ignored (throws in strict mode)
Object.keys(obj); // [] (not enumerable)
Object.getOwnPropertyDescriptor(obj, "id");
// { value: 1, writable: false, enumerable: false, configurable: false }
73. What is the difference between Object.freeze, Object.seal, and Object.preventExtensions?
| Add properties | Delete properties | Change values | |
|---|---|---|---|
preventExtensions |
No | Yes | Yes |
seal |
No | No | Yes |
freeze |
No | No | No |
All three are shallow: a frozen object’s nested objects can still be mutated.
74. What is the difference between a shallow copy and a deep copy?
A shallow copy ({ ...obj }, Object.assign, [...arr]) copies top-level properties; nested objects are still shared. A deep copy duplicates everything. structuredClone is the built-in deep copy: it handles Date, Map, Set, typed arrays, and circular references, but throws on functions and DOM nodes and drops prototypes (class instances become plain objects).
const original = { tags: ["a"], when: new Date(0) };
const shallow = { ...original };
const deep = structuredClone(original);
shallow.tags.push("b");
original.tags; // ["a", "b"] (shared)
deep.tags; // ["a"]
deep.when instanceof Date; // true
JSON.parse(JSON.stringify(obj)) is a weaker deep copy: it turns dates into strings, drops undefined and functions, and throws on cycles.
75. How would you implement a deep clone?
Recurse into arrays and plain objects, and use a WeakMap of already-copied objects so circular references don’t loop forever.
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== "object") return value;
if (seen.has(value)) return seen.get(value);
if (value instanceof Date) return new Date(value);
if (value instanceof Map) {
const copy = new Map();
seen.set(value, copy);
value.forEach((v, k) => copy.set(k, deepClone(v, seen)));
return copy;
}
const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
seen.set(value, copy);
for (const key of Reflect.ownKeys(value)) copy[key] = deepClone(value[key], seen);
return copy;
}
const node = { name: "root" };
node.self = node;
const cloned = deepClone(node);
cloned.self === cloned; // true (cycle preserved)
Practice: Deep Clone
76. How do you compare two objects for deep equality?
Compare primitives with Object.is, then make sure both values are objects of the same kind with the same set of keys, and recurse into each key. Edge cases to mention: NaN, arrays vs objects, dates, and cycles.
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 keysA = Object.keys(a);
if (keysA.length !== Object.keys(b).length) return false;
return keysA.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
}
deepEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }); // true
Practice: Deep Equals
77. What is the difference between for…in and Object.keys?
for...in iterates over enumerable string keys, including inherited ones from the prototype chain. Object.keys (and values, entries) return only the object’s own enumerable string keys. Prefer Object.entries(obj) with for...of.
78. What is the difference between in, hasOwnProperty, and Object.hasOwn?
"key" in obj checks the whole prototype chain. obj.hasOwnProperty("key") checks only own properties, but fails on Object.create(null) objects or objects that override it. Object.hasOwn(obj, "key") (ES2022) is the safe version.
const dict = Object.create(null);
dict.a = 1;
// dict.hasOwnProperty("a"); // TypeError: dict.hasOwnProperty is not a function
Object.hasOwn(dict, "a"); // true
"toString" in {}; // true (inherited)
79. In what order are object keys returned?
Integer-like keys come first in ascending numeric order, then string keys in insertion order, then symbols in insertion order (only through Reflect.ownKeys or Object.getOwnPropertySymbols). If you need guaranteed insertion order for any key, use a Map.
Object.keys({ b: 1, 2: 1, a: 1, 1: 1 }); // ["1", "2", "b", "a"]
80. What are computed property names and shorthand properties?
const field = "email";
const value = "ada@example.com";
const form = {
[field]: value, // computed key
value, // shorthand for value: value
[`${field}Valid`]: true, // computed from an expression
submit() {}, // method shorthand
};
Object.keys(form); // ["email", "value", "emailValid", "submit"]
81. How does object destructuring work?
Destructuring pulls properties into variables, with optional renaming, defaults (used only for undefined), nesting, and a rest object.
const user = { id: 7, profile: { name: "Ada" }, role: undefined, plan: "pro" };
const { id: userId, profile: { name }, role = "viewer", ...rest } = user;
userId; // 7
name; // "Ada"
role; // "viewer"
rest; // { plan: "pro" }
Deep dive: Destructuring examples
82. How do you transform an object’s keys or values?
Convert to entries, map them, and convert back with Object.fromEntries.
const prices = { apple: 1, pear: 2 };
const doubled = Object.fromEntries(
Object.entries(prices).map(([k, v]) => [k, v * 2]),
);
doubled; // { apple: 2, pear: 4 }
Practice: Map Object Entries and Camelize API Payload
83. How does instanceof work?
obj instanceof Ctor walks obj‘s prototype chain and returns true if it finds Ctor.prototype. It fails across realms (an array from an iframe isn’t instanceof Array in the parent), which is why Array.isArray exists.
function myInstanceOf(obj, Ctor) {
let proto = Object.getPrototypeOf(obj);
while (proto) {
if (proto === Ctor.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
myInstanceOf([], Object); // true
84. What does “composition over inheritance” mean in JavaScript?
Instead of deep class hierarchies (FlyingSwimmingDuck extends SwimmingDuck extends Duck), build objects from small, independent behaviors and combine them. Inheritance couples children to every detail of their parents; composition lets you mix only what you need and change parts independently.
const canFly = (state) => ({ fly: () => `${state.name} flies` });
const canSwim = (state) => ({ swim: () => `${state.name} swims` });
const duck = (name) => {
const state = { name };
return { ...canFly(state), ...canSwim(state) };
};
duck("Donald").swim(); // "Donald swims"
85. What is the difference between Object.keys, Object.getOwnPropertyNames, and Reflect.ownKeys?
All three return only own properties, never inherited ones. They differ in whether they include non-enumerable keys and symbol keys, which matters when you write a deep clone or deep equality check that has to copy everything.
| Method | Non-enumerable | Symbols |
|---|---|---|
Object.keys |
No | No |
Object.getOwnPropertyNames |
Yes | No |
Reflect.ownKeys |
Yes | Yes |
None of them include inherited keys.
86. What are the gotchas of JSON.stringify?
undefined, functions, and symbols are dropped from objects and becomenullin arrays.NaNandInfinitybecomenull.- Dates become ISO strings (through
Date.prototype.toJSON) and don’t come back as dates. MapandSetbecome{}.- Circular references and BigInt throw a
TypeError.
JSON.stringify({ a: undefined, b: () => 1, c: NaN, d: [undefined], e: new Map([[1, 2]]) });
// '{"c":null,"d":[null],"e":{}}'
Practice: Build Your Own JSON.stringify
87. What is the difference between host objects and native objects?
Native (built-in) objects are defined by the ECMAScript spec and exist in every environment: Object, Array, Promise, Map. Host objects come from the environment: window, document, and fetch in browsers, and process and Buffer in Node.
Deep dive: Host objects vs native objects
88. What is the difference between mutable and immutable data, and why does it matter?
Mutable data can change in place; immutable data is replaced with a new copy on every change. Immutability makes change detection a cheap reference check (prev !== next), which React, Redux, and memoization rely on. Mutating shared objects causes “it changed and nothing re-rendered” bugs.
const state = { user: { name: "Ada" }, todos: [] };
const next = { ...state, user: { ...state.user, name: "Grace" } };
next.todos === state.todos; // true (unchanged parts are shared)
next.user === state.user; // false
Deep dive: Immutable vs mutable objects. Practice: Immutable Path Update
89. When would you use a factory function instead of a class?
Use a factory when you want true privacy through closures, don’t need instanceof, or want to return different object shapes. Use a class when you’ll create many instances (methods are shared on the prototype instead of recreated per object), need inheritance, or want the clarity of #private fields and static members.
90. How do you safely read and write a value at a nested path?
Reading: split the path and walk with optional chaining. Writing: create missing objects along the way.
const get = (obj, path, fallback) =>
path.split(".").reduce((acc, key) => acc?.[key], obj) ?? fallback;
function set(obj, path, value) {
const keys = path.split(".");
let cur = obj;
keys.slice(0, -1).forEach((k) => { cur = cur[k] ??= {}; });
cur[keys.at(-1)] = value;
return obj;
}
get({ a: { b: { c: 1 } } }, "a.b.c"); // 1
get({}, "a.b", "none"); // "none"
set({}, "user.address.city", "Paris"); // { user: { address: { city: "Paris" } } }
Practice: Read Nested Path and Set Value at Path
Arrays, Strings, and Collections

Find in-depth explanations and practice here: Array Methods: myMap, myFilter, myReduce ->
Array and string questions test whether you know which methods mutate, what they return, and how to pick the right data structure. Many coding rounds start with “implement reduce” or “remove duplicates by key”.
91. What is the difference between map and forEach?
map returns a new array of the callback’s results. forEach returns undefined and is only for side effects. Use map when you want a transformed array; using it just to loop creates a throwaway array and signals the wrong intent. Neither can be stopped early: use for...of with break, or some/find.
Deep dive: Array.forEach vs Array.map
92. How do map, filter, and reduce work? Implement reduce.
map transforms each item, filter keeps items that pass a test, and reduce folds the array into one value by carrying an accumulator. Without an initial value, reduce uses the first element and throws on an empty array.
Array.prototype.myReduce = function (callback, ...initial) {
if (this.length === 0 && initial.length === 0) {
throw new TypeError("Reduce of empty array with no initial value");
}
let i = 0;
let acc = initial.length ? initial[0] : this[i++];
for (; i < this.length; i++) {
if (i in this) acc = callback(acc, this[i], i, this); // skip holes like the native method
}
return acc;
};
[1, 2, 3].myReduce((sum, n) => sum + n, 0); // 6
Practice: Array Methods
93. What is the difference between slice and splice?
slice(start, end) |
splice(start, count, ...items) |
|
|---|---|---|
| Mutates the array | No | Yes |
| Returns | A copy of the selected range | The removed items |
| Typical use | Copy or take a sub-range | Insert, remove, or replace in place |
Deep dive: Array slice vs splice
94. Why does [10, 9, 1].sort() return [1, 10, 9]?
Without a comparator, sort converts items to strings and compares them by UTF-16 code units, so “10” comes before “9”. Pass a comparator that returns a negative number, zero, or a positive number. sort mutates the array and has been guaranteed stable since ES2019.
[10, 9, 1].sort(); // [1, 10, 9]
[10, 9, 1].sort((a, b) => a - b); // [1, 9, 10]
const users = [{ name: "b", age: 30 }, { name: "a", age: 30 }];
users.sort((x, y) => x.age - y.age || x.name.localeCompare(y.name)); // age, then name
95. What are toSorted, toReversed, toSpliced, and with?
ES2023 added non-mutating versions of the mutating array methods. They return a new array and leave the original untouched, which is exactly what React state updates need.
const nums = [3, 1, 2];
nums.toSorted(); // [1, 2, 3]
nums.toReversed(); // [2, 1, 3]
nums.toSpliced(0, 1); // [1, 2]
nums.with(1, 99); // [3, 99, 2]
nums; // [3, 1, 2] (unchanged)
Practice: Copy With Replaced Index
96. What is the difference between find, filter, findIndex, and findLast?
filter returns every match as an array. find returns the first matching item (or undefined) and stops searching. findIndex returns its index (or -1). findLast and findLastIndex (ES2023) search from the end, which is handy for “latest event of type X”.
Practice: Find Last Where
97. What is the difference between includes and indexOf?
Both search with strict equality, with one difference: includes uses SameValueZero, so it finds NaN. indexOf can’t. Use includes for “is it there?” and indexOf when you need the position.
[NaN].includes(NaN); // true
[NaN].indexOf(NaN); // -1
98. How do you remove duplicates from an array?
[...new Set([1, 2, 2, 3])]; // [1, 2, 3]
// Objects: dedupe by key, keeping the first occurrence.
function uniqueBy(items, key) {
const seen = new Set();
return items.filter((x) => !seen.has(x[key]) && seen.add(x[key]));
}
uniqueBy([{ id: 1, v: "a" }, { id: 1, v: "b" }, { id: 2, v: "c" }], "id");
// [{ id: 1, v: "a" }, { id: 2, v: "c" }]
A Set compares objects by reference, so for objects you need a key. Practice: Remove Duplicate Values and Merge Unique by Key
99. How do you flatten a nested array?
arr.flat(depth) is built in (flat(Infinity) for full depth). In interviews, you’re usually asked to implement it, sometimes iteratively to avoid stack overflows.
function flatten(arr, depth = Infinity) {
return depth < 1
? arr.slice()
: arr.reduce((acc, item) =>
acc.concat(Array.isArray(item) ? flatten(item, depth - 1) : item), []);
}
flatten([1, [2, [3, [4]]]], 1); // [1, 2, [3, [4]]]
flatten([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
Practice: Flatten Array With Depth
100. What are array-like objects, and how do you convert them?
Array-likes have a length and indexed elements but no array methods: arguments, NodeList, HTMLCollection, strings. Convert with Array.from(x) or spread ([...x], which needs the object to be iterable). Array.from also takes a map function.
Array.from({ length: 3 }, (_, i) => i * 2); // [0, 2, 4]
101. What is the difference between Array(3) and Array.from({ length: 3 })?
Array(3) creates a sparse array with 3 empty slots (holes). Many methods skip holes, so Array(3).map((_, i) => i) returns [ <3 empty items> ]. Array.from({ length: 3 }) creates [undefined, undefined, undefined], which methods do visit. Use Array.from or Array(3).fill(0).
102. How do you empty an array?
arr.length = 0 empties it in place, so every reference sees an empty array. arr = [] points the variable at a new array and leaves other references with the old contents. Which one is right depends on whether others should see the change.
103. What is the difference between for…of and for…in on arrays?
for...of iterates over values using the iterator protocol. for...in iterates over enumerable property keys as strings, including inherited ones and any extra properties added to the array. Never use for...in on arrays.
const letters = ["a", "b"];
for (const v of letters) console.log(v); // "a", "b"
for (const k in letters) console.log(k); // "0", "1" (strings)
104. How do you group array items by a key?
Object.groupBy and Map.groupBy (ES2024) do it natively. Map.groupBy lets you group by non-string keys.
const orders = [{ status: "paid", id: 1 }, { status: "open", id: 2 }, { status: "paid", id: 3 }];
const byStatus = Object.groupBy(orders, (o) => o.status);
byStatus.paid.map((o) => o.id); // [1, 3]
// Before ES2024:
const grouped = orders.reduce((acc, o) => {
(acc[o.status] ??= []).push(o);
return acc;
}, {});
Practice: Multi-Key Group By and Tally by Key
105. How do you split an array into chunks?
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]]
Practice: Chunk Grid Rows
106. How does array destructuring work?
const [first, , third = "default", ...others] = ["a", "b", undefined, "d", "e"];
first; // "a"
third; // "default"
others; // ["d", "e"]
let x = 1, y = 2;
[x, y] = [y, x]; // swap without a temp variable
107. What is the difference between the spread and rest operators?
Same syntax (...), opposite jobs. Spread expands an iterable or object into individual elements (in calls, array literals, object literals). Rest collects multiple elements into one array or object (in parameters and destructuring).
const nums = [1, 2, 3];
Math.max(...nums); // spread: 3
const [head, ...tail] = nums; // rest: tail is [2, 3]
const merged = { ...{ a: 1 }, b: 2 }; // spread: { a: 1, b: 2 }
Deep dive: Rest vs spread operators
108. When should you use a Map instead of an object?
| Object | Map | |
|---|---|---|
| Key types | Strings and symbols | Any value, including objects |
| Order | Integer keys first, then insertion | Always insertion order |
| Size | Object.keys(o).length |
map.size |
| Inherited keys | Yes, unless Object.create(null) |
No |
| Frequent add/delete | Slower | Optimized for it |
| JSON | Native | Convert with Object.fromEntries |
Use objects for fixed-shape records and JSON. Use Map for dictionaries with dynamic keys, non-string keys, or lots of churn.
Deep dive: Advantages of ES6 Maps and Sets
109. When should you use a Set instead of an array?
Use a Set for unique values and fast membership checks: set.has(x) is effectively constant time, while array.includes(x) scans the whole array. ES2025 added set operations: union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf, and isDisjointFrom.
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
[...a.intersection(b)]; // [2, 3]
[...a.difference(b)]; // [1]
Deep dive: Sets vs arrays
110. What are WeakMap and WeakSet used for?
They hold their keys weakly: if nothing else references a key object, it can be garbage collected along with its entry. Keys must be objects (or non-registered symbols), and you can’t iterate or get the size. Use them to attach data to objects you don’t own without causing leaks: caching per DOM node, private data per instance, or tracking visited objects in a deep clone.
const clickCounts = new WeakMap();
function track(element) {
clickCounts.set(element, (clickCounts.get(element) ?? 0) + 1);
}
// When the element is removed and unreferenced, its entry disappears too.
111. Are strings mutable in JavaScript?
No. Every string method returns a new string. str[0] = "x" is silently ignored (and throws in strict mode). Building a large string in a loop with += is fine in modern engines; for many parts, collecting them in an array and calling join is also common.
112. What are template literals and tagged templates?
Template literals use backticks and support interpolation (${expr}) and multi-line strings. A tagged template passes the literal’s parts to a function, which can process or escape them. Libraries use tags for SQL escaping, CSS-in-JS, and GraphQL.
function upper(strings, ...values) {
return strings.reduce((out, s, i) => out + s + (i < values.length ? String(values[i]).toUpperCase() : ""), "");
}
const lang = "js";
upper`I write ${lang} daily`; // "I write JS daily"
Deep dive: Template literals
113. How do you reverse a string, and what’s the Unicode pitfall?
str.split("").reverse().join("") works for plain ASCII but breaks characters made of two UTF-16 code units, like most emoji. Spreading the string splits by code points, which is better. Characters built from several code points (flags, skin-tone emoji) need Intl.Segmenter.
const s = "hi😀";
s.length; // 4 (the emoji is 2 code units)
s.split("").reverse().join(""); // broken emoji
[...s].reverse().join(""); // "😀ih"
114. How do you check whether a string is a palindrome?
Normalize it (lowercase, strip non-alphanumerics), then compare characters from both ends moving inward. That’s O(n) time and O(1) extra space beyond the normalized string.
function isPalindrome(text) {
const s = text.toLowerCase().replace(/[^a-z0-9]/g, "");
for (let i = 0, j = s.length - 1; i < j; i++, j--) {
if (s[i] !== s[j]) return false;
}
return true;
}
isPalindrome("A man, a plan, a canal: Panama"); // true
Practice: Palindrome Phrase Check
115. How do you check whether two strings are anagrams?
Count characters in one string and decrement for the other. Sorting both strings also works but is O(n log n).
function isAnagram(a, b) {
if (a.length !== b.length) return false;
const counts = new Map();
for (const ch of a) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const ch of b) {
const n = counts.get(ch);
if (!n) return false;
counts.set(ch, n - 1);
}
return true;
}
isAnagram("listen", "silent"); // true
Practice: Anagram Phrase Check
116. How do you find the most frequent words in a text?
Count with a Map, then sort the entries by count. For the top K of a huge list, a heap avoids sorting everything.
function topWords(text, k) {
const counts = new Map();
for (const word of text.toLowerCase().match(/[a-z']+/g) ?? []) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, k).map(([w]) => w);
}
topWords("the cat and the hat and the bat", 2); // ["the", "and"]
Practice: Top K Words
117. What is the difference between replace and replaceAll?
With a string pattern, replace changes only the first match; replaceAll changes every match. With a regex, replace needs the g flag to replace all, and replaceAll throws if the regex lacks g. Both accept a function as the replacement.
"a-b-c".replace("-", "+"); // "a+b-c"
"a-b-c".replaceAll("-", "+"); // "a+b+c"
"price: 10".replace(/\d+/, (n) => n * 2); // "price: 20"
118. Which string methods should you know for interviews?
slice, split, trim/trimStart/trimEnd, padStart/padEnd, startsWith/endsWith/includes, at (negative indexes), repeat, toLowerCase, localeCompare, match/matchAll, and normalize. Prefer slice over the deprecated substr.
"7".padStart(3, "0"); // "007"
"report.pdf".at(-1); // "f"
"ab".repeat(3); // "ababab"
119. How do you compare and sort strings correctly for users?
< and > compare UTF-16 code units, so “Z” sorts before “a” and accented letters end up in odd places. For user-facing sorting, use localeCompare or a reusable Intl.Collator, which also supports numeric sorting (“file2” before “file10”).
["file10", "file2", "File1"].sort(new Intl.Collator("en", { numeric: true, sensitivity: "base" }).compare);
// ["File1", "file2", "file10"]
120. What are typed arrays and ArrayBuffer used for?
An ArrayBuffer is a fixed block of raw binary memory. Typed arrays (Uint8Array, Float32Array, and others) are views over it with a fixed numeric type. You meet them when handling files, images, audio, WebGL/WebGPU, WebSockets with binary data, and transferring large data to a worker without copying.
Asynchronous JavaScript and the Event Loop

Find in-depth explanations and practice here: Event loop: microtasks and macrotasks ->
Async is where JavaScript interviews get hard. Expect an ordering puzzle, a Promise.all implementation, and a question about race conditions in a search box. These are the advanced JavaScript interview questions most candidates are weakest on.
121. What is the event loop?
The event loop is how one JavaScript thread handles asynchronous work. Your code runs on the call stack until it’s empty. Then the loop runs all queued microtasks (promise callbacks), lets the browser render if it’s time, and then takes the next task (a timer, an event, a message) from the task queue. Repeat.
Deep dive: Understanding the JavaScript event loop and the event loop explained with one diagram
122. What are the call stack, the task queue, and the microtask queue?
- Call stack: the functions currently executing. Synchronous code runs here to completion.
- Task (macrotask) queue: callbacks from timers, I/O, UI events, and
postMessage. One task runs per loop iteration. - Microtask queue: promise reactions,
awaitcontinuations,queueMicrotask, andMutationObserver. Drained completely after each task, before rendering.
123. Which APIs create microtasks and which create macrotasks?
| Microtasks | Macrotasks |
|---|---|
Promise.then/catch/finally, code after await, queueMicrotask, MutationObserver |
setTimeout, setInterval, DOM events, MessageChannel, network callbacks, setImmediate (Node) |
requestAnimationFrame is neither: it runs right before the browser paints a frame.
124. What does this code log?
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// 1, 4, 3, 2
“1” and “4” are synchronous. When the stack empties, the microtask queue runs (“3”) before the next task, the timer (“2”).
125. Does setTimeout(fn, 0) run immediately?
No. It schedules a task, which runs only after the current code and all microtasks finish, and possibly after a render. The delay is a minimum, not a guarantee. Browsers clamp nested timers (5+ levels deep) to at least 4ms, and background tabs throttle timers much more.
126. What is a Promise?
A Promise is an object representing a value that will be available later. It’s in one of three states: pending, fulfilled, or rejected. Once settled, it never changes. You read the result with then, catch, or await, and callbacks always run asynchronously, even if the promise is already settled.
Deep dive: Mastering asynchronous JavaScript
127. How does promise chaining work?
then returns a new promise that resolves with whatever the callback returns. If the callback returns a promise, the chain waits for it. If it throws, the new promise rejects and skips to the next catch.
Promise.resolve(2)
.then((n) => n * 2) // 4
.then((n) => Promise.resolve(n + 1)) // waits, then 5
.then((n) => { throw new Error(`bad ${n}`); })
.then(() => console.log("skipped"))
.catch((e) => console.log(e.message)); // "bad 5"
The most common bug: forgetting to return inside a then, so the next step runs immediately with undefined.
128. What is the difference between .then(onSuccess, onError) and .then(onSuccess).catch(onError)?
The second argument of then only handles rejections from the promise before it. It doesn’t catch errors thrown inside onSuccess. A trailing catch handles both.
const boom = () => { throw new Error("in handler"); };
Promise.resolve().then(boom, () => console.log("not called")).catch((e) => console.log("caught:", e.message));
// caught: in handler
129. How does finally work?
finally runs on both fulfillment and rejection, receives no arguments, and passes the original result or error through unchanged. If the finally callback throws or returns a rejected promise, that rejection replaces the original outcome. Use it for cleanup like hiding a spinner.
130. What is the difference between Promise.all, allSettled, race, and any?
| Method | Fulfills when | Rejects when | Use it for |
|---|---|---|---|
all |
All fulfill (array of values) | The first rejection | Requests that all must succeed |
allSettled |
All settle (array of status objects) | Never | Independent requests; show partial results |
race |
The first to settle fulfills | The first to settle rejects | Timeouts |
any |
The first to fulfill | All reject (AggregateError) |
Fastest mirror or fallback sources |
Practice: Promise Methods
131. How would you implement Promise.all?
Return a new promise, track results by index (not by completion order), count fulfillments, and reject on the first error. Handle the empty array and non-promise values.
function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const items = [...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;
if (--remaining === 0) resolve(results);
}, reject);
});
});
}
promiseAll([1, Promise.resolve(2), new Promise((r) => setTimeout(r, 10, 3))]).then(console.log); // [1, 2, 3]
132. How would you implement Promise.allSettled?
Map every input to a promise that always fulfills with a status object, then reuse Promise.all.
const allSettled = (items) =>
Promise.all([...items].map((item) =>
Promise.resolve(item).then(
(value) => ({ status: "fulfilled", value }),
(reason) => ({ status: "rejected", reason }),
)));
Practice: Settled Pool Map
133. What does async/await do under the hood?
An async function always returns a promise. await pauses the function, subscribes to the awaited promise, and resumes the rest of the function as a microtask when it settles. It’s built on the same machinery as generators plus promises; it doesn’t block the thread.
134. How do you handle errors with async/await?
Wrap awaits in try/catch, or attach .catch to the returned promise at the call site. A rejected await throws like a synchronous error, so finally works for cleanup.
async function loadUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch only rejects on network errors
return await res.json();
} catch (err) {
console.error("loadUser failed", err);
throw err; // let the caller decide what to show
}
}
Note that fetch doesn’t reject on 404 or 500. You have to check res.ok.
135. What is the difference between sequential and parallel awaits?
Awaiting independent requests one after another adds their latencies. Start them together and await them together.
const wait = (ms, v) => new Promise((r) => setTimeout(r, ms, v));
// Sequential: about 200ms
const a = await wait(100, "a");
const b = await wait(100, "b");
// Parallel: about 100ms
const [c, d] = await Promise.all([wait(100, "c"), wait(100, "d")]);
136. Why doesn’t await work inside forEach?
forEach ignores the promise your async callback returns, so it doesn’t wait. Code after the loop runs before the work finishes, and errors become unhandled rejections. Use for...of to go one at a time, or Promise.all(items.map(...)) to go in parallel.
const ids = [1, 2, 3];
const save = async (id) => id;
// Wrong: ids.forEach(async (id) => await save(id));
for (const id of ids) await save(id); // sequential
await Promise.all(ids.map(save)); // parallel
137. What is Promise.withResolvers?
ES2024 added Promise.withResolvers(), which returns { promise, resolve, reject }. It replaces the “deferred” pattern of capturing resolve from inside the executor, useful when the code that settles the promise lives somewhere else (an event handler, a queue).
const { promise, resolve } = Promise.withResolvers();
setTimeout(() => resolve("ready"), 10);
console.log(await promise); // "ready"
Practice: Deferred Promise Handle
138. What happens to an unhandled promise rejection?
Browsers fire an unhandledrejection event on window and log an error. Node, since version 15, crashes the process by default. Always end chains with a catch or await inside a try, and report rejections to your error monitoring from a global unhandledrejection listener.
139. How do you cancel a fetch request?
Pass an AbortController‘s signal to fetch and call abort(). The fetch rejects with an AbortError, which you usually ignore. AbortSignal.timeout(ms) gives you a signal that aborts on its own.
const controller = new AbortController();
fetch("/api/search?q=re", { signal: controller.signal })
.catch((e) => { if (e.name !== "AbortError") throw e; });
controller.abort(); // cancel it, for example when the user types again
// Built-in timeout:
// fetch(url, { signal: AbortSignal.timeout(5000) });
Practice: Abortable Delay
140. How do you add a timeout to any promise?
Race it against a promise that rejects after N milliseconds, and clear the timer either way so it doesn’t keep running.
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
A timeout doesn’t stop the underlying work. To actually cancel a request, combine it with AbortController. Practice: Promise Deadline Guard
141. How do you retry a failed request with exponential backoff?
async function retry(fn, { retries = 3, baseMs = 200 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt >= retries) throw err;
const delay = baseMs * 2 ** attempt * (0.5 + Math.random()); // jitter avoids synchronized retries
await new Promise((r) => setTimeout(r, delay));
}
}
}
Only retry errors that can succeed later (network failures, 429, 503), not 400 or 401. Practice: API Retry
142. How do you limit how many async tasks run at once?
Start N workers that each pull the next item from a shared index until none are left. Results keep their original order.
async function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i], i);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return results;
}
Practice: Map Async With Limit and Asynchronous Request Queue
143. How do you convert a callback-based function into a promise?
Wrap it in a promise and translate Node-style (err, result) callbacks into reject/resolve. Node ships this as util.promisify.
const promisify = (fn) => (...args) =>
new Promise((resolve, reject) => {
fn(...args, (err, result) => (err ? reject(err) : resolve(result)));
});
const legacyRead = (name, cb) => setTimeout(() => cb(null, `contents of ${name}`), 5);
await promisify(legacyRead)("a.txt"); // "contents of a.txt"
Practice: Promisify Any Function
144. How do you prevent race conditions in a search-as-you-type input?
Responses can arrive out of order, so a slow response for “re” can overwrite the results for “react”. Fix it by aborting the previous request when a new one starts, or by ignoring any response that isn’t for the latest query. Debounce the input to reduce requests, but debouncing alone doesn’t fix ordering.
let controller;
async function search(query) {
controller?.abort();
controller = new AbortController();
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal });
render(await res.json());
} catch (e) {
if (e.name !== "AbortError") throw e;
}
}
function render(results) { console.log(results); }
Practice: Autocomplete Search List
145. How do you write a sleep function?
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await sleep(10); // pauses this async function only, not the thread
146. When do you use requestAnimationFrame instead of setTimeout?
Use requestAnimationFrame for anything visual. It runs right before the next paint, matches the display’s refresh rate, and pauses in background tabs. A setTimeout animation can fire mid-frame, drop frames, or do work the user never sees. Base the animation on the timestamp argument, not a fixed step, so it runs at the same speed on 60Hz and 120Hz screens.
Practice: Animate Element To The Right
147. What is queueMicrotask used for?
queueMicrotask(fn) runs fn after the current synchronous code but before any timer or render. Libraries use it to batch several synchronous updates into one notification, the same way promise callbacks are batched. It’s cheaper and clearer than Promise.resolve().then(fn) for that purpose.
148. Can microtasks block rendering?
Yes. The microtask queue is drained completely before the browser can render, and microtasks can queue more microtasks. A promise chain that keeps scheduling itself freezes the page just like an infinite loop. Long work should be split across tasks (setTimeout, scheduler.postTask where supported) or moved to a worker.
149. What is the difference between process.nextTick and setImmediate in Node?
process.nextTick callbacks run right after the current operation, before promise microtasks. setImmediate runs in the “check” phase of the Node event loop, after I/O callbacks. The names are backwards from what you’d guess. Prefer queueMicrotask or setImmediate; heavy use of nextTick can starve I/O.
150. What is a thenable?
Any object with a then method. Promises adopt thenables: Promise.resolve(thenable) and await thenable call its then and follow the result. That’s how promises from different libraries work together. It’s also a trap: an object that happens to have a then property gets “unwrapped” when you resolve a promise with it.
const thenable = { then(resolve) { resolve(42); } };
console.log(await thenable); // 42
Practice: Coerce to Promise
151. How would you implement a basic Promise?
Track the state, value, and a list of callbacks. then returns a new promise and either queues the handler (pending) or schedules it as a microtask (settled). Handlers must run asynchronously, and a returned promise must be adopted.
class MyPromise {
#state = "pending";
#value;
#handlers = [];
constructor(executor) {
const settle = (state) => (value) => {
if (this.#state !== "pending") return;
if (state === "fulfilled" && value && typeof value.then === "function") {
return value.then(settle("fulfilled"), settle("rejected")); // adopt thenables
}
this.#state = state;
this.#value = value;
this.#handlers.forEach((h) => queueMicrotask(h));
};
try { executor(settle("fulfilled"), settle("rejected")); } catch (e) { settle("rejected")(e); }
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
const run = () => {
const cb = this.#state === "fulfilled" ? onFulfilled : onRejected;
if (typeof cb !== "function") return (this.#state === "fulfilled" ? resolve : reject)(this.#value);
try { resolve(cb(this.#value)); } catch (e) { reject(e); }
};
this.#state === "pending" ? this.#handlers.push(run) : queueMicrotask(run);
});
}
catch(onRejected) { return this.then(undefined, onRejected); }
}
new MyPromise((r) => setTimeout(r, 5, 1)).then((v) => v + 1).then(console.log); // 2
Practice: Build a Custom Promise
152. What are async iterators and for await…of?
An async iterator’s next() returns a promise. for await...of consumes them one value at a time, which fits paginated APIs, streams, and event sources. Async generators (async function*) are the easiest way to write one.
async function* pages() {
for (let page = 1; page <= 3; page++) {
yield await Promise.resolve({ page, items: [page * 10] });
}
}
for await (const { page } of pages()) console.log(page); // 1, 2, 3
153. When should you use a Web Worker?
When CPU-heavy work (parsing a large file, image processing, diffing big data, running a model) would block the main thread for more than a frame or two. Workers run JavaScript in parallel on another thread with no DOM access and communicate through postMessage. Transfer large ArrayBuffers instead of copying them. Workers don’t help with network waits, which are already non-blocking.
154. What does this async function puzzle log?
async function a() {
console.log("a1");
await b();
console.log("a2");
}
async function b() { console.log("b"); }
console.log("start");
a();
Promise.resolve().then(() => console.log("p"));
console.log("end");
// start, a1, b, end, a2, p
An async function runs synchronously until its first await, so “a1” and “b” print right away. The rest of a is queued as a microtask before the .then callback, so “a2” prints before “p”.
155. Callbacks vs promises vs async/await: how do you compare them?
| Callbacks | Promises | async/await | |
|---|---|---|---|
| Composition | Nested | Chained, combinators | Reads like synchronous code |
| Errors | Manual at every level | One catch |
try/catch |
| Still useful for | Events and streams of values | Parallelism (all, race) |
Most sequential async logic |
Deep dive: Synchronous vs asynchronous functions
Modern JavaScript: ES2015 to ES2025

Find in-depth explanations and practice here: ES6 vs ES2015 versioning ->
Interviewers ask about modern features to see whether your knowledge is current. You don’t need every proposal, but you should know modules, iterators, generators, and what changed in the last few yearly releases.
156. What is the difference between ES6 and ES2015?
They’re the same release. ES6 (the sixth edition of ECMAScript) was renamed ES2015 when TC39 switched to yearly releases. Every June since, a new edition ships with whatever proposals reached stage 4: ES2016, ES2017, and so on up to ES2025.
157. What were the most important features in ES2015?
let and const, arrow functions, classes, modules, promises, template literals, destructuring, default and rest parameters, spread, Map/Set/WeakMap/WeakSet, symbols, iterators and for...of, generators, Proxy/Reflect, and typed arrays. Most modern JavaScript is built on this release.
158. What is the difference between ES modules and CommonJS?
| ES modules | CommonJS | |
|---|---|---|
| Syntax | import / export |
require / module.exports |
| Loading | Asynchronous, analyzed before running | Synchronous, at runtime |
| Bindings | Live (importers see updates) | A copy of exports at require time |
| Tree shaking | Yes (static structure) | Hard |
| Top-level await | Yes | No |
| Strict mode | Always | Opt-in |
| Where | Browsers, modern Node | Node (legacy default) |
159. Should you use named or default exports?
Many teams prefer named exports: the name is the same everywhere it’s imported, editors can auto-import and rename it reliably, and it’s harder to import the wrong thing. Default exports are fine for one-thing-per-file modules and are required by some frameworks (for example, Next.js pages).
160. What is dynamic import()?
import(path) loads a module at runtime and returns a promise of its namespace. Bundlers turn it into a separate chunk, which is the basis of code splitting: load the chart library only when the user opens the chart.
async function openEditor() {
const { createEditor } = await import("./editor.js"); // fetched on demand
return createEditor();
}
Deep dive: Code splitting and lazy loading
161. What is top-level await?
ES2022 allows await at the top level of a module. Modules that import it wait until it resolves. It’s useful for loading config or initializing a dependency, but a slow top-level await delays every importer, so keep it out of widely shared modules.
162. What is the iteration protocol, and how do you make an object iterable?
An object is iterable if it has a [Symbol.iterator] method that returns an iterator: an object with next() returning { value, done }. for...of, spread, destructuring, Array.from, and Promise.all all use it.
class Range {
constructor(from, to) { this.from = from; this.to = to; }
*[Symbol.iterator]() {
for (let n = this.from; n <= this.to; n++) yield n;
}
}
[...new Range(1, 4)]; // [1, 2, 3, 4]
163. What are generators, and when are they useful?
A generator function (function*) returns an iterator and can pause at each yield, resuming when next() is called. They’re useful for lazy or infinite sequences, custom iterables, and step-by-step processes. Before async/await, libraries like co used generators to write async code; Redux-Saga still does.
function* ids() {
let id = 1;
while (true) yield id++;
}
const gen = ids();
gen.next().value; // 1
gen.next().value; // 2
Practice: Sequential ID Generator
164. What are symbols used for?
A symbol is a unique, immutable primitive. Use symbols as property keys that won’t collide with other code and don’t show up in for...in, Object.keys, or JSON.stringify. Well-known symbols let you hook into language behavior: Symbol.iterator (iteration), Symbol.asyncIterator, Symbol.toPrimitive (conversion), and Symbol.hasInstance (instanceof). Symbol.for(key) returns a shared symbol from a global registry.
165. What are Proxy and Reflect used for?
A Proxy wraps an object and intercepts operations (get, set, delete, has, function calls) with “traps”. Reflect provides the default behavior for each trap, so you can add logic and then forward. Vue 3 and MobX use proxies for reactivity; you’ll also see them in validation and API mocks.
function observable(target, onChange) {
return new Proxy(target, {
set(obj, key, value, receiver) {
const ok = Reflect.set(obj, key, value, receiver);
onChange(key, value);
return ok;
},
});
}
const state = observable({ count: 0 }, (k, v) => console.log(`${String(k)} -> ${v}`));
state.count++; // "count -> 1"
Practice: Observable Attribute Model
166. What are the logical assignment operators?
ES2021 added ||=, &&=, and ??=. They assign only when needed, which also means the right side isn’t evaluated otherwise.
const opts = { retries: 0, title: "" };
opts.retries ??= 3; // stays 0 (not null or undefined)
opts.title ||= "Untitled"; // "Untitled" ("" is falsy)
const cache = {};
(cache.users ??= []).push("ada"); // create on first use
167. What smaller syntax features should you know?
- Exponent operator:
2 ** 10(ES2016). - Numeric separators:
1_000_000(ES2021). - Optional catch binding:
try { } catch { }with no error variable (ES2019). at()with negative indexes on arrays and strings (ES2022).- Trailing commas in function parameters (ES2017).
- Hashbang
#!/usr/bin/env nodeat the top of scripts (ES2023).
168. What is Error cause?
ES2022 lets you attach the original error when you throw a higher-level one: new Error(message, { cause }). You keep the context (“failed to load profile”) without losing the root error, and error monitoring tools can show the chain.
try {
JSON.parse("{bad json");
} catch (err) {
const wrapped = new Error("Could not read settings", { cause: err });
console.log(wrapped.cause instanceof SyntaxError); // true
}
169. What are class fields and static initialization blocks?
Class fields (ES2022) declare instance properties in the class body instead of the constructor, including private #fields. A static { } block runs once when the class is defined, for setup that needs more than one expression.
class Config {
static defaults;
static {
Config.defaults = Object.freeze({ theme: "dark", retries: 3 });
}
theme = Config.defaults.theme; // instance field
}
new Config().theme; // "dark"
170. What are WeakRef and FinalizationRegistry, and should you use them?
WeakRef holds a reference that doesn’t prevent garbage collection; deref() returns the object or undefined if it was collected. FinalizationRegistry runs a callback some time after an object is collected. Garbage collection timing is unpredictable, so the spec itself advises avoiding them unless you’re building something like a cache of expensive objects. Never rely on them for correctness.
171. What are iterator helpers?
ES2025 added methods like map, filter, take, drop, flatMap, reduce, and toArray directly on iterators. They’re lazy: values are processed one at a time, so you can work with huge or infinite sequences without building intermediate arrays.
function* naturals() { let n = 1; while (true) yield n++; }
naturals().filter((n) => n % 2 === 0).map((n) => n * n).take(3).toArray(); // [4, 16, 36]
172. What else landed in ES2025?
- Set methods:
union,intersection,difference, and friends (Q109). Promise.try(fn): runsfnand always returns a promise, turning synchronous throws into rejections.- Import attributes and JSON modules:
import config from "./config.json" with { type: "json" }. RegExp.escapefor safely building a regex from user input, plus inline regex modifiers.Float16ArrayandMath.f16roundfor half-precision numbers (graphics and ML).
173. What changed in ES2023 and ES2024?
ES2023: findLast/findLastIndex, the copying array methods (toSorted, toReversed, toSpliced, with), symbols as WeakMap keys, and hashbang support. ES2024: Object.groupBy/Map.groupBy, Promise.withResolvers, resizable ArrayBuffers, String.prototype.isWellFormed, and the regex v flag.
174. What modern regex features should you know?
const date = /(?<year>\d{4})-(?<month>\d{2})/; // named groups
"2026-11".match(date).groups.year; // "2026"
"price: $42".match(/(?<=\$)\d+/)[0]; // lookbehind: "42"
[..."a1b2".matchAll(/\d/g)].map((m) => m[0]); // ["1", "2"]
Also: the s flag (dot matches newlines), the d flag (match indices), the u and v flags for Unicode, and RegExp.escape (ES2025).
175. What can the Intl APIs do?
They format and compare values by locale without libraries: Intl.NumberFormat (currency, units, compact “1.2K”), Intl.DateTimeFormat, Intl.RelativeTimeFormat (“3 days ago”), Intl.PluralRules, Intl.ListFormat (“a, b, and c”), Intl.Collator (sorting), and Intl.Segmenter (splitting text into graphemes or words).
new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(1234.5); // "$1,234.50"
new Intl.NumberFormat("en", { notation: "compact" }).format(1200); // "1.2K"
new Intl.ListFormat("en", { type: "conjunction" }).format(["a", "b", "c"]); // "a, b, and c"
176. What’s wrong with Date, and what is Temporal?
Date is mutable, months are zero-based, it only knows UTC and the user’s local time zone, and parsing non-ISO strings is inconsistent across browsers. Temporal is a TC39 proposal that replaces it with immutable types (PlainDate, ZonedDateTime, Duration) and real time zone support. It reached stage 3 and is shipping in browsers gradually, so check support or use a polyfill before relying on it.
new Date(2026, 0, 31).getMonth(); // 0 (January is month 0)
177. What is the difference between a polyfill and a transpiler?
A polyfill adds a missing API at runtime by implementing it in JavaScript (Array.prototype.at, structuredClone). A transpiler (Babel, TypeScript, SWC, esbuild) rewrites new syntax into older syntax at build time (optional chaining, class fields). Syntax can’t be polyfilled, and APIs can’t be transpiled; you often need both.
Deep dive: JavaScript polyfills
178. How do you decide which JavaScript features you can use?
Define supported browsers in a browserslist config based on your analytics. Build tools read it to decide what to transpile, and core-js can inject only the polyfills those browsers need. Check MDN’s compatibility tables or Baseline status for anything new, and feature-detect at runtime when a fallback exists.
179. How does the TC39 process work?
TC39 is the committee that evolves JavaScript. Proposals move through stages: 0 (idea), 1 (proposal: problem worth solving), 2 (draft spec text), 2.7 (spec approved, waiting for tests), 3 (ready to implement, feedback from engines), and 4 (finished, included in the next yearly edition). Features at stage 3 often ship behind flags or in some browsers before stage 4.
180. What does TypeScript add, and does it change runtime behavior?
TypeScript adds static types checked at build time: catching wrong property names, missing null checks, and broken refactors before the code runs. Types are erased at compile time, so they don’t validate data at runtime. For API responses or user input, you still need runtime validation (Zod, Valibot, or hand-written checks).
DOM, Events, and Browser APIs

Find in-depth explanations and practice here: Event propagation in JavaScript ->
Frontend interviews test JavaScript in the browser, not just the language. Expect questions on events, rendering, storage, and security, and at least one “implement this DOM API” coding question.
181. What is the DOM?
The Document Object Model is the browser’s tree of objects representing the HTML document. JavaScript reads and changes the page through it: document.querySelector, element.classList, appendChild. The DOM is a host API, not part of JavaScript itself, which is why Node doesn’t have document.
182. What is the difference between querySelectorAll and getElementsByClassName?
querySelectorAll takes any CSS selector and returns a static NodeList: a snapshot that doesn’t change. getElementsByClassName and getElementsByTagName return a live HTMLCollection that updates as the DOM changes, which can cause infinite loops if you add matching elements while iterating. getElementById returns one element and is the fastest lookup.
Practice: getElementsByClassName and querySelectorAll
183. What are the phases of event propagation?
- Capture: the event travels from
windowdown to the target’s parent. - Target: the event reaches the element that triggered it.
- Bubble: the event travels back up to
window.
Listeners run in the bubble phase by default. Pass { capture: true } to run during capture. A few events don’t bubble (focus, blur, mouseenter); use focusin/focusout if you need bubbling.
184. What is event bubbling?
After an event fires on an element, it fires on each ancestor in turn. A click on a button inside a card also triggers click listeners on the card, the list, and the document. Bubbling is what makes event delegation possible.
Deep dive: Event bubbling in JavaScript
185. What is event delegation?
Instead of a listener on every child, attach one listener to a common ancestor and check event.target to see which child was hit. It uses less memory, and children added later work automatically.
document.querySelector("#todo-list")?.addEventListener("click", (event) => {
const button = event.target.closest("button[data-action='delete']");
if (!button || !event.currentTarget.contains(button)) return;
button.closest("li").remove();
});
closest handles clicks on an icon inside the button. Deep dive: Event delegation. Practice: Delegate Container Events
186. What is the difference between preventDefault, stopPropagation, and stopImmediatePropagation?
| Method | Effect |
|---|---|
preventDefault() |
Cancels the browser’s default action (following a link, submitting a form). The event still propagates. |
stopPropagation() |
Stops the event from reaching other elements. Other listeners on the current element still run. |
stopImmediatePropagation() |
Stops propagation and also skips the remaining listeners on the current element. |
Use stopPropagation sparingly: it breaks analytics, “click outside to close” logic, and delegated handlers further up.
187. What is the difference between event.target and event.currentTarget?
target is the element where the event started (the innermost element clicked). currentTarget is the element whose listener is currently running. In delegation, currentTarget is the container and target is the child.
188. What options does addEventListener accept?
once: true: remove the listener after the first call.passive: true: promise not to callpreventDefault, so the browser can scroll without waiting for your handler. Use it fortouchstart,touchmove, andwheel.capture: true: run in the capture phase.signal: anAbortSignalthat removes the listener when aborted.
189. How do you remove event listeners cleanly?
removeEventListener needs the exact same function reference and capture flag, so inline arrow functions can’t be removed. An AbortController removes many listeners at once, which is ideal for component cleanup.
function mountDropdown(root) {
const controller = new AbortController();
const { signal } = controller;
document.addEventListener("keydown", (e) => { if (e.key === "Escape") root.hidden = true; }, { signal });
document.addEventListener("click", (e) => { if (!root.contains(e.target)) root.hidden = true; }, { signal });
return () => controller.abort(); // removes both listeners
}
190. What is the difference between attributes and properties?
Attributes are defined in HTML and are always strings (getAttribute("value")). Properties live on the DOM object and can be any type (input.value, input.checked). For many elements they start in sync but diverge: typing into an input changes the value property, while the value attribute keeps the initial default.
Deep dive: Attributes vs properties
191. What is the difference between innerHTML, textContent, and innerText?
innerHTML parses a string as HTML, which is an XSS risk with any user data. textContent reads or sets raw text, including hidden elements, and doesn’t trigger layout. innerText returns the text as rendered (respects CSS, so hidden text is excluded) and forces a layout to compute it. To insert user content, use textContent.
192. How do you add many elements to the DOM efficiently?
Build them off-DOM and insert once. A DocumentFragment (or element.append(...nodes)) causes a single insertion instead of one per element.
function renderList(container, items) {
const fragment = document.createDocumentFragment();
for (const item of items) {
const li = document.createElement("li");
li.textContent = item.label; // safe against XSS
fragment.append(li);
}
container.replaceChildren(fragment);
}
Practice: Create DOM. Deep dive: Adding a span to a div
193. What is the difference between reflow and repaint?
Reflow (layout) recalculates the size and position of elements. It’s triggered by changes to geometry: width, font size, adding elements. Repaint redraws pixels without changing layout: color, background, visibility. Reflow is more expensive and usually causes a repaint too. Changing transform and opacity can skip both and run on the compositor.
Deep dive: Reflow vs repaint
194. What is layout thrashing, and how do you avoid it?
Layout thrashing happens when code alternates DOM writes and layout reads (offsetHeight, getBoundingClientRect) in a loop, forcing a synchronous reflow on every read. Batch all reads first, then all writes, or schedule writes with requestAnimationFrame.
function equalizeHeights(boxes) {
const max = Math.max(...boxes.map((b) => b.offsetHeight)); // all reads
boxes.forEach((b) => { b.style.height = `${max}px`; }); // then all writes
}
195. What is the critical rendering path?
The steps from HTML to pixels: parse HTML into the DOM, parse CSS into the CSSOM, combine them into the render tree, compute layout, paint, and composite layers. CSS blocks rendering and synchronous scripts block parsing, so optimizing it means inlining critical CSS, deferring scripts, and reducing what’s needed for the first paint.
Deep dive: The critical rendering path
196. What happens when you type a URL and press Enter?
DNS lookup, TCP and TLS handshakes (or QUIC for HTTP/3), the HTTP request, the server response, then HTML parsing, subresource requests (CSS, JS, images), the critical rendering path, and JavaScript execution. Interviewers want the overview first, then depth in whichever step they pick.
Deep dive: From URL to screen
197. What is the difference between async and defer on script tags?
| Attribute | Download | Runs | Order kept |
|---|---|---|---|
| None | Blocks parsing | Immediately | Yes |
async |
In parallel | As soon as it’s downloaded (pauses parsing) | No |
defer |
In parallel | After parsing, before DOMContentLoaded |
Yes |
Use defer for app scripts and async for independent scripts like analytics. Module scripts (type="module") are deferred by default.
198. What is the difference between DOMContentLoaded and load?
DOMContentLoaded fires when the HTML is parsed and deferred scripts have run, without waiting for images, stylesheets, or iframes. load fires when everything, including images, has finished loading. Run setup code on DOMContentLoaded (or just use defer).
199. What is the difference between localStorage, sessionStorage, cookies, and IndexedDB?
| Lifetime | Capacity | Sent to the server | API | |
|---|---|---|---|---|
localStorage |
Until cleared | About 5MB per origin | No | Synchronous strings |
sessionStorage |
Until the tab closes | About 5MB | No | Synchronous strings |
| Cookies | Set by Expires/Max-Age |
About 4KB each | Yes, with every request | String parsing |
| IndexedDB | Until cleared | Large (a share of disk) | No | Asynchronous, structured data |
Never store tokens or secrets in localStorage: any XSS can read it. Use HttpOnly cookies for session tokens. Practice: Expiring Storage Wrapper
200. What do the HttpOnly, Secure, and SameSite cookie attributes do?
HttpOnly: JavaScript can’t read the cookie (document.cookie), which limits XSS damage.Secure: sent only over HTTPS.SameSite: controls cross-site sending.Strictnever sends it cross-site,Lax(the browser default) sends it on top-level navigations, andNonesends it always but requiresSecure. It’s the main defense against CSRF.
201. What is CORS?
Cross-Origin Resource Sharing lets a server tell the browser which other origins may read its responses. By default, the same-origin policy blocks reading cross-origin responses. The server opts in with Access-Control-Allow-Origin. Requests with non-simple methods or headers trigger a preflight OPTIONS request first. CORS is enforced by browsers; it doesn’t protect the server from other clients like curl.
Deep dive: Understanding CORS
202. What is the difference between GET and POST?
GET retrieves data, puts parameters in the URL, should have no side effects, and can be cached and bookmarked. POST sends data in the body to create or change something and isn’t cached by default. Both are visible to anyone who can inspect the traffic unless you use HTTPS.
Deep dive: HTTP GET vs POST
203. What is IntersectionObserver used for?
It tells you when an element enters or leaves the viewport (or another container) without scroll listeners or layout reads on every scroll. Use it for infinite scroll, lazy-loading images, impression tracking, and starting animations on reveal.
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
loadNextPage();
observer.unobserve(entry.target);
}
}
}, { rootMargin: "200px" }); // start loading before the sentinel is visible
function loadNextPage() {}
Practice: Intersection Observer and Infinite Scrolling News Feed
204. What are MutationObserver and ResizeObserver?
MutationObserver reports DOM changes (children added, attributes changed, text edited), batched as a microtask. It’s useful for reacting to third-party DOM changes. ResizeObserver reports when an element’s size changes, which is better than listening to window.resize when you need container-based layouts or charts that resize with their parent.
205. How do you create and dispatch custom events?
const cart = new EventTarget();
cart.addEventListener("item-added", (e) => console.log("added", e.detail.sku));
cart.dispatchEvent(new CustomEvent("item-added", { detail: { sku: "A1" } }));
// "added A1"
On DOM elements, pass { bubbles: true } if ancestors should hear it. EventTarget can be extended by any class, giving you a built-in event emitter. Practice: EventTarget
206. How does client-side routing work?
The History API changes the URL without a page load: history.pushState(state, "", "/settings") adds an entry, and replaceState replaces the current one. When the user presses back or forward, the browser fires popstate, and the router renders the matching view. Links are intercepted so clicks call pushState instead of navigating. The server must return the app for every route, or deep links 404.
Practice: Navigation
207. What is a service worker?
A script that runs in the background, separate from the page, and can intercept network requests from pages in its scope. It powers offline support, caching strategies (cache first, network first, stale-while-revalidate), push notifications, and background sync. It requires HTTPS, has no DOM access, and has a lifecycle (install, activate, fetch) that makes updates tricky: a new version waits until old tabs close unless you call skipWaiting.
208. How do windows and iframes communicate safely?
With postMessage. The sender should pass a specific target origin instead of "*", and the receiver must check event.origin before trusting the message. Never eval or inject message contents as HTML.
window.addEventListener("message", (event) => {
if (event.origin !== "https://checkout.example.com") return; // ignore everyone else
if (event.data?.type === "payment-complete") showReceipt(event.data.orderId);
});
function showReceipt(id) { console.log(id); }
209. What is the Shadow DOM?
The Shadow DOM attaches an encapsulated DOM subtree to an element. Styles inside don’t leak out, and outside styles don’t leak in (except inherited properties and CSS custom properties). It’s the foundation of Web Components, along with custom elements (customElements.define) and <template>/<slot>. Don’t confuse it with React’s virtual DOM, which is an in-memory representation for diffing.
Deep dive: Virtual DOM vs Shadow DOM
210. How do you find the same node in two identical DOM trees?
Record the path from the node up to its root as child indexes, then replay that path down the other tree.
function findCorresponding(rootA, rootB, target) {
const path = [];
for (let node = target; node !== rootA; node = node.parentNode) {
path.push([...node.parentNode.children].indexOf(node));
}
return path.reduceRight((node, index) => node.children[index], rootB);
}
O(depth × siblings) time, O(depth) space. Practice: Find Corresponding Node and Traverse DOM
Memory, Performance, and Security

Find in-depth explanations and practice here: Identifying memory leaks in browser applications ->
These questions separate people who write JavaScript from people who ship it. Expect them in mid-level and senior loops, often as follow-ups: “this works, but what happens with 10,000 items?” or “is this safe with user input?”
211. How does garbage collection work in JavaScript?
Engines use reachability: anything reachable from the roots (global object, the current call stack, active closures) is kept, and everything else can be freed. The core algorithm is mark-and-sweep: mark everything reachable, then sweep the rest. V8 adds a generational collector, because most objects die young: new objects are collected frequently and cheaply, and survivors are promoted to an older space that’s collected less often. Circular references aren’t a problem as long as the whole cycle is unreachable.
212. What are the most common memory leaks in frontend apps?
- Event listeners on
windowordocumentthat are never removed. setIntervaltimers that are never cleared.- Detached DOM nodes still referenced from JavaScript (a cached element removed from the page).
- Unbounded caches and maps that grow forever.
- Closures in long-lived callbacks that capture large objects.
- Subscriptions (WebSockets, observables, stores) not unsubscribed on unmount.
213. How do you find a memory leak?
Reproduce the suspected action (open and close a modal) several times, then compare heap snapshots in Chrome DevTools’ Memory panel. Look for object counts that only grow, filter for “Detached” to find removed DOM nodes still in memory, and follow the retainers path to the variable keeping them alive. The allocation timeline shows when leaking objects were created.
214. What is a detached DOM node?
An element removed from the document but still referenced by JavaScript, so it can’t be garbage collected. A single reference to a detached parent keeps its whole subtree alive. Common causes: storing elements in arrays or maps, and listeners or closures that reference removed elements.
215. How do you measure JavaScript performance?
Use the Performance panel in DevTools to record real interactions and find long tasks. In code, performance.now() gives high-resolution timing, and the User Timing API (performance.mark and performance.measure) shows your own markers in the profiler. Measure real user data with the PerformanceObserver API or a library like web-vitals, since your laptop isn’t a mid-range phone.
performance.mark("filter-start");
const result = Array.from({ length: 100000 }, (_, i) => i).filter((n) => n % 7 === 0);
performance.mark("filter-end");
const { duration } = performance.measure("filter", "filter-start", "filter-end");
console.log(result.length, `${duration.toFixed(1)}ms`);
216. What is a long task, and how do you break one up?
A long task is anything that blocks the main thread for more than 50ms. During it, the page can’t respond to input, which hurts Interaction to Next Paint (INP). Break work into chunks and yield to the browser between them, so clicks and paints can happen.
const yieldToMain = () => new Promise((resolve) => setTimeout(resolve, 0));
async function processAll(items, handle) {
let last = performance.now();
for (const item of items) {
handle(item);
if (performance.now() - last > 40) { // stay under the 50ms budget
await yieldToMain();
last = performance.now();
}
}
}
Where supported, scheduler.yield() does the same thing while keeping your task’s priority. Deep dive: Debugging INP
217. How do you render a list of 10,000 items without freezing the page?
Virtualize it: render only the rows visible in the viewport plus a small buffer, and use spacers (or absolute positioning) to keep the scroll height correct. As the user scrolls, compute which slice is visible and render just that. Fixed-height rows make the math trivial; variable heights need measurement and caching.
Deep dive: List virtualization and Virtualizing variable-height lists
218. How do you reduce JavaScript bundle size?
Code-split by route and by heavy feature with dynamic import(), rely on tree shaking (ES modules, side-effect-free packages), replace heavy dependencies (a full date library for one format call), and analyze the bundle with a visualizer. Less JavaScript means less to download, parse, and execute, and parsing costs the most on slow phones.
Deep dive: Code splitting and lazy loading
219. How do you lazy-load images?
Add loading="lazy" to images below the fold, and always set width and height (or aspect-ratio) so the layout doesn’t shift when they load. Don’t lazy-load the hero image: it’s usually the Largest Contentful Paint element, so give it fetchpriority="high" instead. For custom behavior, use an IntersectionObserver.
220. How do object shapes affect performance in V8?
V8 gives objects with the same properties added in the same order a shared hidden class (shape), and inline caches make property access on them fast. Adding properties in different orders, deleting properties, or mixing types in the same field creates more shapes and slower polymorphic code. In practice: initialize all fields in the constructor, avoid delete on hot objects, and keep arrays of one type. Measure before micro-optimizing.
221. What is the time complexity of common JavaScript operations?
| Operation | Complexity |
|---|---|
arr.push, arr.pop, arr[i] |
O(1) |
arr.shift, arr.unshift, arr.splice at the start |
O(n) (re-indexes) |
arr.includes, indexOf, find |
O(n) |
arr.sort |
O(n log n) |
set.has, map.get, obj[key] |
O(1) average |
Spread or slice copy |
O(n) |
A shift() inside a loop makes a queue O(n2); use an index pointer or a real queue. Practice: Constant Time Queue
222. What is XSS, and how do you prevent it?
Cross-site scripting is when an attacker gets their script to run on your page, where it can steal data, act as the user, or read tokens. Types: stored (saved in your database), reflected (in the URL), and DOM-based (your JavaScript writes untrusted input into the page). Prevent it by treating all data as text: use textContent, rely on framework escaping (React escapes by default), avoid innerHTML/dangerouslySetInnerHTML with user data or sanitize it first, validate URLs, and add a Content Security Policy.
223. What is a Content Security Policy?
An HTTP header that tells the browser which sources of scripts, styles, images, and connections are allowed. A strict CSP (scripts only from your domain or with a per-request nonce, no inline event handlers, no eval) means that even if an attacker injects markup, their script won’t run. Roll it out with Content-Security-Policy-Report-Only first to find what breaks.
224. What is CSRF, and how do you defend against it?
Cross-site request forgery tricks a logged-in user’s browser into sending a request to your site from another site, using the user’s cookies. Defenses: SameSite=Lax or Strict cookies, anti-CSRF tokens for state-changing requests, checking the Origin header, and never changing state on GET requests.
225. What is prototype pollution?
An attack where untrusted input sets properties on Object.prototype, usually through an unsafe deep merge or path setter given a key like __proto__ or constructor.prototype. Every object then inherits the attacker’s property, which can bypass checks (if (user.isAdmin)).
function safeMerge(target, source) {
for (const key of Object.keys(source)) {
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
const value = source[key];
if (value && typeof value === "object" && !Array.isArray(value)) {
target[key] = safeMerge(target[key] ?? {}, value);
} else {
target[key] = value;
}
}
return target;
}
safeMerge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));
({}).isAdmin; // undefined (not polluted)
Also use Object.create(null) or Map for dictionaries keyed by user input. Practice: Merge Config Overrides
226. Why is eval dangerous?
eval runs a string as code with access to the current scope. If any part of the string comes from users, it’s code injection. It also blocks engine optimizations and is blocked by a strict CSP. new Function(string) and string arguments to setTimeout have the same problem. To parse data, use JSON.parse.
227. How do you safely render user-provided HTML?
Sanitize it with an allowlist: keep only known-safe tags (b, i, a, p) and attributes, strip event handler attributes (onerror), and reject javascript: URLs. Use a maintained library like DOMPurify rather than regexes, and sanitize on output (in the browser, at render time) as well as on input. The built-in Sanitizer API is coming to browsers for the same purpose.
Practice: Allowlist HTML Sanitizer
228. What is clickjacking?
An attacker loads your site in an invisible iframe and tricks users into clicking buttons on it (“delete account”) while they think they’re clicking something else. Prevent it with the Content-Security-Policy: frame-ancestors 'none' (or 'self') header, or the older X-Frame-Options: DENY.
229. Where should a frontend store authentication tokens?
The safest default is an HttpOnly, Secure, SameSite cookie set by the server: JavaScript can’t read it, so XSS can’t steal it (though XSS can still make requests as the user). localStorage is readable by any script on the page. If you must handle tokens in JavaScript, keep a short-lived access token in memory and refresh it through an HttpOnly cookie.
230. How do you reduce third-party and supply-chain risk?
Commit lockfiles, review new dependencies (maintenance, size, install scripts), run npm audit or a similar scanner in CI, pin versions, and keep dependencies updated. For scripts loaded from a CDN, use Subresource Integrity (integrity="sha384-...") so a modified file is refused.
231. What is the difference between Math.random and crypto.getRandomValues?
Math.random is fast but predictable, so it’s fine for shuffling UI or picking colors but not for anything security-related. crypto.getRandomValues and crypto.randomUUID() use a cryptographically secure generator. Use them for IDs that must not be guessable, tokens, and nonces.
crypto.randomUUID(); // e.g. "3b241101-e2bb-4255-8caf-4136c566a962"
232. How do you validate a URL before putting it in an href?
Parse it with the URL constructor and allow only expected protocols. Otherwise, a value like javascript:alert(1) runs code when clicked.
function safeHref(input) {
try {
const url = new URL(input, "https://frontendlead.com");
return ["http:", "https:", "mailto:"].includes(url.protocol) ? url.href : "#";
} catch {
return "#";
}
}
safeHref("javascript:alert(1)"); // "#"
safeHref("/blog"); // "https://frontendlead.com/blog"
233. How would you rate-limit calls on the client?
Track timestamps of recent calls in a sliding window and reject (or queue) calls that exceed the limit. Client-side limits protect your own backend from bugs and spammy UIs; real enforcement must still happen on the server.
function rateLimit(fn, limit, windowMs) {
const calls = [];
return (...args) => {
const now = Date.now();
while (calls.length && now - calls[0] >= windowMs) calls.shift();
if (calls.length >= limit) return false;
calls.push(now);
fn(...args);
return true;
};
}
Practice: Rate Limiter
234. What are Core Web Vitals?
Google’s user experience metrics: Largest Contentful Paint (LCP, loading: good is 2.5s or less), Interaction to Next Paint (INP, responsiveness: 200ms or less), and Cumulative Layout Shift (CLS, visual stability: 0.1 or less). They’re measured at the 75th percentile of real users. JavaScript affects all three: large bundles delay LCP, long tasks hurt INP, and late-inserted content causes CLS.
Deep dive: Core Web Vitals
235. How would you approach a page that “feels slow”?
Measure before changing anything. Check field data (CrUX, RUM) to see which metric is bad and for whom, then reproduce with a throttled CPU and network in the Performance panel. Fix the biggest cause first: for slow loading, look at the LCP element, render-blocking resources, and bundle size; for slow interactions, find long tasks and unnecessary re-renders; for layout shifts, reserve space for images, ads, and fonts. Then verify with the same measurements.
What Does This Code Log? Output Questions

Find in-depth explanations and practice here: Frontend trivia interview prep guide ->
Output questions are the tricky JavaScript interview questions phone screens love. Read each snippet, decide what it logs, then check the answer. When you explain it out loud, name the rule (hoisting, coercion, microtasks), not just the result. All snippets run as ES modules, so strict mode applies.
236. What does this log? (hoisting)
console.log(typeof foo, typeof bar);
var foo = 1;
function bar() {}
Answer: undefined function. Both declarations are hoisted, but only the function gets its value early; var foo is undefined until its line runs.
237. What does this log? (shadowing and hoisting)
var x = 1;
function f() {
console.log(x);
var x = 2;
}
f();
Answer: undefined. The inner var x is hoisted to the top of f, shadowing the outer x before it’s assigned.
238. What does this log? (closures in loops)
const fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map((f) => f()));
Answer: [3, 3, 3]. All three closures share one function-scoped i. With let, it’s [0, 1, 2].
239. What does this log? (detached method)
const obj = { name: "A", getName() { return this?.name; } };
const get = obj.getName;
console.log(obj.getName(), get());
Answer: A undefined. get() is a plain call, so this is undefined in strict mode. Without the ?., it would throw.
240. What does this log? (arrow functions inside methods)
const counter = {
count: 0,
start() {
[1, 2].forEach(() => this.count++);
return this.count;
},
};
console.log(counter.start());
Answer: 2. The arrow callbacks inherit this from start, which is counter. With function () {} callbacks, this would be undefined and it would throw.
241. What does this log? (microtasks vs timers)
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve()
.then(() => {
console.log("C");
setTimeout(() => console.log("D"), 0);
})
.then(() => console.log("E"));
queueMicrotask(() => console.log("F"));
console.log("G");
Answer: A G C F E B D. Synchronous code first (A, G). Then microtasks in order: C, then F (queued before E existed), then E. Then timers in the order they were scheduled: B, then D.
242. What does this log? (the Promise executor)
new Promise((resolve) => {
console.log(1);
resolve(2);
console.log(3);
}).then(console.log);
console.log(4);
Answer: 1 3 4 2. The executor runs synchronously, and resolve doesn’t stop it. The then callback runs as a microtask after the synchronous code.
243. What do these expressions evaluate to? (+ with arrays and objects)
const results = [[] + [], [] + {}, [1, 2] + [3], {} + []];
console.log(JSON.stringify(results));
Answer: ["","[object Object]","1,23","[object Object]"]. + converts objects to primitives with toString: [] becomes "", [1, 2] becomes "1,2", and {} becomes "[object Object]", then the strings are concatenated.
244. What does this log? (number precision)
console.log(0.1 + 0.2 === 0.3, 9007199254740992 === 9007199254740993);
Answer: false true. Floating-point rounding makes the first false, and both large literals round to the same double because they’re beyond Number.MAX_SAFE_INTEGER.
245. What does this log? (typeof typeof)
console.log(typeof typeof 1);
Answer: string. typeof 1 is the string "number", and typeof "number" is "string".
246. What does this log? (objects as keys)
const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
Answer: 456. Object keys are converted to strings, and both b and c become "[object Object]", so the second assignment overwrites the first. Use a Map for object keys.
247. What does this log? (evaluation order)
let x = 10;
const fn = () => { x = 20; return x; };
console.log(x, fn(), x);
Answer: 10 20 20. Arguments are evaluated left to right, so the first x is read before fn changes it.
248. What does this log? (changing prototypes)
function Person(name) { this.name = name; }
Person.prototype.greet = function () { return `Hi ${this.name}`; };
const p = new Person("Ada");
Person.prototype.greet = function () { return `Hello ${this.name}`; };
console.log(p.greet());
Person.prototype = { greet() { return "replaced"; } };
console.log(p.greet());
Answer: Hello Ada, then Hello Ada again. Changing a method on the existing prototype object affects existing instances (it’s a live link). Replacing Person.prototype with a new object only affects instances created afterward; p still links to the old object.
249. What does this log? (arrow function braces)
console.log([1, 2, 3].map((n) => { n * 2; }));
Answer: [undefined, undefined, undefined]. Curly braces make a function body, which needs an explicit return. Use (n) => n * 2. To return an object literal, wrap it in parentheses: () => ({ a: 1 }).
250. What does this log? (sparse arrays)
const arr = [1, 2, 3];
arr[10] = 11;
console.log(arr.length, arr.filter(() => true).length);
Answer: 11 4. Assigning index 10 sets length to 11 and leaves 7 holes. filter skips holes, so only 4 real elements pass.
251. What does this log? (async return values)
async function f() { return 1; }
console.log(f());
f().then(console.log);
Answer: a fulfilled promise (Promise { 1 } in Node), then 1. An async function always returns a promise, even when it returns a plain value.
252. What does this log? (try/finally)
function f() {
try { return "try"; } finally { console.log("finally"); }
}
function g() {
try { return "try"; } finally { return "finally"; } // eslint flags this: no-unsafe-finally
}
console.log(f());
console.log(g());
Answer: finally, try, then finally. finally always runs before the function returns. A return inside finally overrides the earlier return (and would swallow a thrown error), which is why linters ban it.
253. What does this log? (Object.freeze)
const frozen = Object.freeze({ a: 1, nested: { b: 1 } });
frozen.nested.b = 2;
console.log(frozen.nested.b);
try {
frozen.a = 2;
} catch (e) {
console.log(e.constructor.name);
}
Answer: 2, then TypeError. Freezing is shallow, so the nested object is still mutable. Writing to a frozen property throws in strict mode (modules and classes); in a sloppy script, it fails silently.
254. What does this log? (default values and null)
const { a = 1, b = 2 } = { a: null, b: undefined };
console.log(a, b);
Answer: null 2. Defaults apply only to undefined. null is a real value, which is a common source of bugs with API responses.
255. What does this log? (loose equality edge cases)
console.log(null == 0, null >= 0, undefined == 0, NaN == NaN, [] == ![]);
Answer: false true false false true. null only loosely equals undefined, but relational operators convert it to 0, so null >= 0 is true. NaN never equals anything. In [] == ![], ![] is false, then both sides become 0.
JavaScript Coding Interview Questions

Find in-depth explanations and practice here: JavaScript coding questions ->
Frontend coding rounds rarely ask LeetCode puzzles. They ask you to build the utilities you use every day: debounce, an event emitter, classnames, a DOM query. The first 15 questions below have full solutions. The next 20 summarize real FrontendLead problems with the key idea, so you can solve them in the browser with tests. The full list of 75 is at the end of this section.
In the interview: restate the API, ask about edge cases (empty input, this, errors, cancellation), write the happy path, then handle the edges and say the complexity.
256. Implement debounce.
Return a function that delays calling fn until wait ms have passed since the last call. Keep the latest arguments and this, and add cancel so components can clean up.
function debounce(fn, wait) {
let timer;
function debounced(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
}
debounced.cancel = () => clearTimeout(timer);
return debounced;
}
const log = debounce((q) => console.log("search", q), 50);
log("r"); log("re"); log("react"); // only "search react" after 50ms
Follow-ups: a leading option (fire on the first call), flush, and a maxWait. Practice: Debounce I, Debounce II, Debounce III
257. Implement throttle.
Call fn at most once per wait ms. This version fires immediately, then once more at the end of the window with the latest arguments, so the final position of a scroll or drag isn’t lost.
function throttle(fn, wait) {
let last = 0;
let timer = null;
let pending = null;
return function throttled(...args) {
const now = Date.now();
const remaining = wait - (now - last);
if (remaining <= 0) {
last = now;
fn.apply(this, args);
} else {
pending = [this, args];
timer ??= setTimeout(() => {
last = Date.now();
timer = null;
fn.apply(...pending);
}, remaining);
}
};
}
Practice: Throttle and Throttle II
258. Implement an event emitter.
Support on, off, once, and emit. Store listeners per event in a Map of arrays, return an unsubscribe function from on, and iterate over a copy in emit so listeners that unsubscribe during emit don’t break the loop.
class EventEmitter {
#events = new Map();
on(name, listener) {
if (!this.#events.has(name)) this.#events.set(name, []);
this.#events.get(name).push(listener);
return () => this.off(name, listener);
}
off(name, listener) {
const list = this.#events.get(name);
if (!list) return;
const i = list.indexOf(listener);
if (i !== -1) list.splice(i, 1);
}
once(name, listener) {
const off = this.on(name, (...args) => { off(); listener(...args); });
return off;
}
emit(name, ...args) {
const list = this.#events.get(name);
if (!list?.length) return false;
[...list].forEach((listener) => listener(...args));
return true;
}
}
const bus = new EventEmitter();
bus.once("login", (user) => console.log("welcome", user));
bus.emit("login", "ada"); // "welcome ada"
bus.emit("login", "ada"); // nothing, the once listener is gone
Practice: Event Emitter and Event Emitter II
259. Flatten a nested object into dot-separated keys.
Recurse into plain objects and build the key path as you go. Decide with the interviewer how to treat arrays (as objects with index keys, or as leaf values) and empty objects.
function flattenObject(obj, prefix = "", out = {}) {
for (const [key, value] of Object.entries(obj)) {
const path = prefix ? `${prefix}.${key}` : key;
if (value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length) {
flattenObject(value, path, out);
} else {
out[path] = value;
}
}
return out;
}
flattenObject({ a: 1, b: { c: 2, d: { e: 3 } }, f: [1, 2] });
// { a: 1, "b.c": 2, "b.d.e": 3, f: [1, 2] }
Practice: Flatten III, Flatten IV, Flatten V, and the reverse, Expand Dotted Keys
260. Implement classnames.
Accept strings, numbers, arrays (recursively), and objects whose truthy values include their keys. Skip falsy values.
function classNames(...args) {
const out = [];
for (const arg of args) {
if (!arg) continue;
if (typeof arg === "string" || typeof arg === "number") out.push(arg);
else if (Array.isArray(arg)) { const inner = classNames(...arg); if (inner) out.push(inner); }
else if (typeof arg === "object") {
for (const [key, on] of Object.entries(arg)) if (on) out.push(key);
}
}
return out.join(" ");
}
classNames("btn", { active: true, disabled: false }, ["lg", null, ["primary"]]); // "btn active lg primary"
Practice: ClassNames
261. Implement getElementsByClassName.
Walk the subtree under the root (not the root itself) and collect elements whose class list contains every requested class, in document order.
function getElementsByClassName(root, classNames) {
const wanted = classNames.trim().split(/\s+/);
const result = [];
const visit = (el) => {
for (const child of el.children) {
if (wanted.every((c) => child.classList.contains(c))) result.push(child);
visit(child);
}
};
visit(root);
return result;
}
O(n × k) for n elements and k classes. Mention that the native version returns a live collection; yours is a snapshot. Practice: getElementsByClassName
262. Implement an LRU cache.
A Map keeps insertion order, so re-inserting a key on access moves it to the “most recent” end, and the first key is always the least recently used. Both operations are O(1).
class LRUCache {
#map = new Map();
constructor(capacity) { this.capacity = capacity; }
get(key) {
if (!this.#map.has(key)) return undefined;
const value = this.#map.get(key);
this.#map.delete(key);
this.#map.set(key, value);
return value;
}
set(key, value) {
this.#map.delete(key);
this.#map.set(key, value);
if (this.#map.size > this.capacity) this.#map.delete(this.#map.keys().next().value);
}
}
const cache = new LRUCache(2);
cache.set("a", 1); cache.set("b", 2); cache.get("a"); cache.set("c", 3);
cache.get("b"); // undefined ("b" was least recently used)
263. Implement clearAllTimeouts.
Wrap setTimeout and clearTimeout to track active timer ids in a Set, removing each id when its timer fires or is cleared.
const activeTimers = new Set();
const nativeSetTimeout = globalThis.setTimeout;
const nativeClearTimeout = globalThis.clearTimeout;
globalThis.setTimeout = (fn, delay, ...args) => {
const id = nativeSetTimeout(() => { activeTimers.delete(id); fn(...args); }, delay);
activeTimers.add(id);
return id;
};
globalThis.clearTimeout = (id) => { activeTimers.delete(id); nativeClearTimeout(id); };
function clearAllTimeouts() {
activeTimers.forEach((id) => nativeClearTimeout(id));
activeTimers.clear();
}
Practice: ClearAllTimeouts and ClearAllIntervals
264. Implement setInterval with a linearly increasing delay.
mySetInterval(fn, delay, period) waits delay + period * count before each run. A real setInterval can’t change its delay, so chain setTimeout calls, and return an id that a matching clear function can use to stop the chain.
const intervals = new Map();
let nextId = 1;
function mySetInterval(fn, delay, period) {
const id = nextId++;
let count = 0;
const schedule = () => {
intervals.set(id, setTimeout(() => {
fn();
count++;
schedule();
}, delay + period * count));
};
schedule();
return id;
}
function myClearInterval(id) {
clearTimeout(intervals.get(id));
intervals.delete(id);
}
Practice: Set Interval with Linear Delay
265. Merge identical in-flight API calls.
Cache the promise, not the result, keyed by the request. Concurrent callers with the same key share one network request. Remove failed entries so a later call can retry.
function createDedupedGet(getAPI) {
const cache = new Map();
return function get(path, config = {}) {
const key = JSON.stringify([path, config]);
if (!cache.has(key)) {
cache.set(key, getAPI(path, config).catch((err) => {
cache.delete(key); // don't cache failures
throw err;
}));
}
return cache.get(key);
};
}
let calls = 0;
const get = createDedupedGet(async (path) => { calls++; return { path }; });
await Promise.all([get("/me"), get("/me"), get("/me")]);
console.log(calls); // 1
Ask whether results should expire (add a timestamp and TTL) and whether keys like { a, b } and { b, a } should match (sort keys before stringifying). Practice: Merge Identical API Calls
266. Calculate total salaries in a nested company structure.
Each node is either a department (an object of sub-departments) or an array of employees. Recurse on objects and sum salaries in arrays.
function calculateTotalSalaries(node) {
if (Array.isArray(node)) return node.reduce((sum, e) => sum + e.salary, 0);
return Object.values(node).reduce((sum, child) => sum + calculateTotalSalaries(child), 0);
}
calculateTotalSalaries({
engineering: { frontend: [{ name: "Ada", salary: 100 }], backend: [{ name: "Linus", salary: 120 }] },
sales: [{ name: "Grace", salary: 90 }],
}); // 310
Practice: Total Salaries
267. Fetch APIs in parallel and return the highest-priority success.
The URLs are ordered by priority. Start all requests at once, then pick the first fulfilled result in priority order; reject if all fail.
async function fetchHighestPriority(urls, fetcher) {
const results = await Promise.allSettled(urls.map((url) => fetcher(url)));
const winner = results.find((r) => r.status === "fulfilled");
if (!winner) throw new AggregateError(results.map((r) => r.reason), "All requests failed");
return winner.value;
}
Strong follow-up: you don’t have to wait for every request. As soon as the top-priority request succeeds, or all higher-priority ones have failed, you can resolve. Practice: API Confirmation
268. Serialize a DOM tree into a virtual DOM object.
Turn each element into { type, props, children }, where text nodes become strings. This is the reverse of rendering, and it shows you understand what React elements are.
function toVirtual(node) {
if (node.nodeType === Node.TEXT_NODE) return node.textContent;
const props = {};
for (const { name, value } of node.attributes) props[name === "class" ? "className" : name] = value;
return {
type: node.tagName.toLowerCase(),
props,
children: [...node.childNodes]
.filter((c) => c.nodeType === Node.ELEMENT_NODE || c.textContent.trim())
.map(toVirtual),
};
}
Practice: Virtual DOM I, then the reverse direction in Virtual DOM II and Virtual DOM III
269. Highlight every occurrence of a word inside an element.
Don’t rewrite innerHTML: it destroys event listeners and is an XSS risk. Walk the text nodes, split each one around matches, and wrap matches in <mark>.
function highlight(root, word) {
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(`(${escaped})`, "gi");
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const textNodes = [];
while (walker.nextNode()) textNodes.push(walker.currentNode);
for (const node of textNodes) {
if (!pattern.test(node.data)) continue;
pattern.lastIndex = 0;
const fragment = document.createDocumentFragment();
node.data.split(pattern).forEach((part, i) => {
if (i % 2) {
const mark = document.createElement("mark");
mark.textContent = part;
fragment.append(mark);
} else if (part) {
fragment.append(part);
}
});
node.replaceWith(fragment);
}
}
Collect text nodes first: modifying the tree while walking it skips nodes. Escaping the word keeps characters like . or ( from breaking the regex. Practice: Text Highlighter and Highlight Search Matches
270. Implement a minimal test framework with describe, it, and expect.
const results = [];
let currentSuite = "";
function describe(name, fn) {
currentSuite = name;
fn();
currentSuite = "";
}
function it(name, fn) {
try {
fn();
results.push({ name: `${currentSuite} > ${name}`, passed: true });
} catch (err) {
results.push({ name: `${currentSuite} > ${name}`, passed: false, error: err.message });
}
}
function expect(actual) {
return {
toBe(expected) {
if (!Object.is(actual, expected)) throw new Error(`Expected ${String(expected)}, got ${String(actual)}`);
},
toEqual(expected) {
if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error("Values are not deeply equal");
},
};
}
describe("math", () => {
it("adds", () => expect(1 + 1).toBe(2));
it("fails", () => expect([1]).toEqual([2]));
});
console.log(results.map((r) => `${r.passed ? "PASS" : "FAIL"} ${r.name}`)); // ["PASS math > adds", "FAIL math > fails"]
Follow-ups: async tests (await the returned promise), nested suites (keep a stack of names), and beforeEach hooks. Practice: Testing Framework and Scoped Test Hooks
271. Exclude items that match a set of rules.
excludeItems removes objects that match any exclusion rule (a property and a value). The naive version runs a nested loop over items and rules. The improvement interviewers want: group the rules into a Map of key to a Set of values first, so each item check is O(number of keys) instead of O(number of rules).
Practice: Improve a Function
272. Filter and merge gym session data by user.
Given sessions with a user, duration, and equipment, return sessions filtered by options and merged per user (total duration, combined unique equipment). Key idea: one pass that groups by user in a Map, a Set for equipment, then apply the filters and sorting the options ask for.
Practice: Gym Sessions
273. Build a phone number input that formats as you type.
Strip non-digits, cap the length, and rebuild the display format (for example, (555) 123-4567) on every input event. The tricky part is the cursor: reformatting moves it to the end, so compute where it should go based on how many digits precede it.
Practice: Phone Number Parser
274. Implement a NodeStore keyed by DOM nodes.
Build set, get, and has with DOM nodes as keys. If Map is off limits, tag each node with a unique id stored in a non-enumerable property (or a symbol), then use a plain object keyed by that id. Mention that a WeakMap is the real-world answer because it doesn’t leak removed nodes.
Practice: Node Store and Node Store (ES5)
275. Render styled ranges for a rich text editor.
Given a string and [start, end, tag] style ranges, produce nested HTML. Key idea: turn ranges into open and close events at each index, sort them, and walk the string, closing and reopening tags when ranges overlap so the HTML stays valid.
Practice: Parser for Rich Text Editor
276. Aggregate skill endorsements.
Group endorsements by skill into { skill, users, count } summaries, sorted by count. A single reduce into a Map, then Array.from(map.values()).sort(...), is O(n log k) for k skills.
Practice: Skill Endorsements
277. Build a masonry layout in vanilla JavaScript.
Place each item in the currently shortest column. Track column heights in an array, absolutely position each item at that column’s x and current height, then add the item’s height to it. Recompute on resize (debounced) and after images load.
Practice: Masonry Grid
278. Find the next right sibling in a tree.
Unlike nextElementSibling, the next right node can belong to a different parent at the same depth. Do a breadth-first traversal level by level; the target’s next right sibling is the node right after it in its level, or null if it’s last.
Practice: Next Right Sibling
279. Build a stream that subscribers can listen to.
A Stream class with subscribe(fn) and push(value): every push calls each subscriber, and subscribe returns an unsubscribe function. It’s an event emitter with one event, and the base idea behind RxJS observables.
Practice: Stream and RxJS Observable
280. Build a text histogram of number frequencies.
Count occurrences with a Map, find the maximum count for the chart height, then print rows from top to bottom, marking a bar in each column whose count reaches that row. It tests counting plus careful string building.
Practice: Histogram
281. Find the K most frequent text nodes on a page.
Walk text nodes with a TreeWalker (NodeFilter.SHOW_TEXT), trim them, skip empty ones, count with a Map, then sort by frequency and take K. Mention a heap for very large pages.
Practice: K Most Text Nodes
282. Filter objects that match all criteria.
findMatches(data, match) returns the objects whose fields equal every key in match: data.filter((item) => Object.entries(match).every(([k, v]) => item[k] === v)). Discuss nested criteria and case-insensitive matching as extensions.
Practice: Filtering Matching JSON
283. Build hierarchical checkboxes with an indeterminate state.
Checking a parent checks all descendants; changing a child updates every ancestor to checked, unchecked, or indeterminate (some children checked). Use one delegated change listener, update down the tree, then walk up with closest.
Practice: Hierarchical Checkbox
284. Build a fake timer for tests.
Replace setTimeout, clearTimeout, and Date.now with versions driven by a virtual clock. Keep pending timers sorted by fire time (and creation order for ties); tick(ms) advances the clock and runs every timer that’s due, including timers scheduled by other timers.
Practice: Fake Timer
285. Get all text between two DOM nodes.
Walk text nodes in document order with a TreeWalker, start collecting after you pass node1, and stop at node2. compareDocumentPosition tells you which node comes first if the order isn’t guaranteed.
Practice: Get Text Between Nodes
286. Reorder an array in place by new indexes.
Given items and newIndexes, move each item to its new position by mutating the array. The O(1)-extra-space approach follows cycles: swap the item at i into its target position and swap the index array in step, until position i holds the right item.
Practice: Reorder Array With New Indexes
287. Implement undo and redo with commands.
Each edit is a command with apply and revert. Keep an undo stack and a redo stack: running a command pushes it to undo and clears redo; undo pops, reverts, and pushes to redo. Group several commands into one batch so a multi-cell paste undoes as one step.
Practice: Command Undo Stack
288. Compile a placeholder template once and render it many times.
compileTemplate("Hi {{name}}") returns render(values). Parse the template a single time into an array of static strings and placeholder names, so each render is a fast join instead of a regex scan. Decide what missing values render as, and escape HTML if the output goes into the DOM.
Practice: Compiled Placeholder Template and Escaped Template Renderer
289. Implement String.prototype.myRepeat.
Repeat a string N times without the native repeat. The simple loop is O(n) concatenations; the clever version doubles the string (binary exponentiation), needing only O(log n) concatenations. Handle 0 (empty string) and reject negative counts with a RangeError, like the native method.
Practice: String Repeater
290. Log events with a configurable delay.
Build a logger that sends events to a fake server after a delay and logs each with the time elapsed since the logger was created. It tests timers, closures over a start time, and keeping events in order when sends overlap.
Practice: Event Logger I and Event Logger II
The full list: 75 JavaScript coding interview questions to practice
These are the frontend coding questions that come up again and again in real interviews: utilities, DOM work, async control, and small UI builds. Each one opens in the FrontendLead editor with tests and a written and video solution.
Advanced JavaScript Interview Questions for Experienced Developers

Find in-depth explanations and practice here: Layered frontend architecture ->
These are the JavaScript interview questions for experienced and senior developers. There’s rarely one right answer. Interviewers grade whether your decisions come with reasons, trade-offs, and an example from real work.
291. How do you design the API of a reusable JavaScript utility?
Start from the call site. Keep required arguments positional and put optional settings in an options object with defaults (debounce(fn, 300, { leading: true })), so new options don’t break callers. Be consistent about sync versus async (never sometimes-async), return values instead of mutating inputs, throw typed errors for misuse, and provide cleanup (cancel, unsubscribe) for anything that holds timers or listeners.
292. How do you structure a large JavaScript codebase?
Group by feature rather than by file type, so everything for “checkout” lives together. Inside, separate layers: UI components, state and view logic, a data layer (API clients, caching), and shared utilities. Dependencies point one way (UI depends on data, never the reverse), and features import each other only through a public index file. Enforce the boundaries with lint rules, not just convention.
Deep dive: MVVM in frontend applications
293. When do you choose a functional style versus classes in JavaScript?
Functional style (pure functions, immutable data, composition) fits data transformation, UI rendering, and reducers: easy to test and reason about. Classes fit long-lived objects with internal state and a clear lifecycle: a WebSocket client, a cache, an editor model. Most good JavaScript mixes both. The wrong choice is deep inheritance hierarchies for code that’s really just data flowing through functions.
Deep dive: Functional vs object-oriented programming
294. How do you handle errors in a large frontend app?
- Classify: expected errors (validation, 404, offline) are shown to the user with a recovery path; unexpected errors are reported.
- Boundaries: catch at the edges (route-level error boundaries, API client wrappers) instead of
try/catcheverywhere. - Context: wrap errors with
{ cause }so reports show the chain. - Monitoring: global
errorandunhandledrejectionhandlers send reports with release, route, and user context to a tool like Sentry. - Never swallow: an empty
catchturns a crash into silent data corruption.
295. How do you test asynchronous JavaScript?
Return or await the promise in the test so the runner waits. Use fake timers to control setTimeout-based code (debounce, retries) instead of real waits, mock the network at the boundary (MSW or a fake fetch), and assert on outcomes, not internals. Test the unhappy paths: rejection, timeout, cancellation, and out-of-order responses.
Deep dive: Unit tests vs functional and integration tests. Practice: Fake Timer
296. How do you keep code quality high across a team?
Automate everything that doesn’t need judgment: formatting (Prettier), linting with rules that catch bugs (no-floating-promises, exhaustive-deps), type checking, and tests in CI on every pull request. Reviews then focus on design, naming, and edge cases. Keep the rules small enough that people don’t learn to ignore them.
Deep dive: Code quality with linting tools
297. How does a JavaScript bundler work?
It starts from entry points, parses each module to find its imports, and builds a dependency graph. Then it transforms code (TypeScript, JSX, newer syntax), removes unused exports (tree shaking), splits the graph into chunks at dynamic import() boundaries and shared dependencies, minifies, and writes files with content hashes for long-term caching. Dev servers like Vite skip bundling in development and serve native ES modules instead.
298. How would you build a small observable state store from scratch?
function createStore(reducer, initialState) {
let state = initialState;
const listeners = new Set();
return {
getState: () => state,
dispatch(action) {
const next = reducer(state, action);
if (Object.is(next, state)) return; // skip no-op updates
state = next;
listeners.forEach((listener) => listener(state));
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
}
const store = createStore((s, a) => (a.type === "inc" ? { count: s.count + 1 } : s), { count: 0 });
store.subscribe((s) => console.log(s.count));
store.dispatch({ type: "inc" }); // 1
Discuss selectors (subscribe to a slice to avoid unnecessary updates), batching, and how React’s useSyncExternalStore connects a store like this to components. Practice: Reducer State Store and Observable Autorun Engine
299. How do middleware pipelines work?
Each middleware receives the context and a next function, can run code before and after calling next, and can stop the chain by not calling it. That “onion” model powers Express, Koa, Redux middleware, and fetch interceptors.
function compose(middlewares) {
return (ctx) => {
const dispatch = (i) => (i < middlewares.length ? middlewares[i](ctx, () => dispatch(i + 1)) : undefined);
return dispatch(0);
};
}
const log = [];
compose([
(ctx, next) => { log.push("a in"); next(); log.push("a out"); },
(ctx, next) => { log.push("b"); next(); },
])({});
log; // ["a in", "b", "a out"]
Practice: Onion Middleware Runner
300. What is the difference between progressive enhancement and graceful degradation?
Progressive enhancement starts with a baseline that works without JavaScript (server-rendered HTML, real links and forms) and layers interactivity on top. Graceful degradation builds the full experience first and adds fallbacks for weaker environments. Progressive enhancement is more resilient: when a script fails to load or errors, the core task still works.
Deep dive: Progressive enhancement vs graceful degradation
301. How do you keep JavaScript-driven UI accessible?
Use native elements first (button, a, dialog, details) because they come with keyboard support and semantics. When you build custom widgets, manage focus (move it into a modal, trap it there, return it on close), support the expected keys, keep ARIA states in sync (aria-expanded, aria-selected), and announce async updates with a live region.
Deep dive: Web accessibility. Practice: Stacked Focus Traps
302. How would you implement feature flags on the frontend?
Fetch flags once at startup (or render them into the HTML to avoid a flash), expose them through a small client with a typed isEnabled(flag) and safe defaults when the service is down, and evaluate targeting (user, percentage rollout) on the server so rules and secrets aren’t shipped to the browser. Remove flags once rolled out; old flags become dead code paths nobody tests.
Practice: Build a Feature Flag
303. Polling, long polling, server-sent events, or WebSockets: how do you choose?
| Approach | Direction | Use it for |
|---|---|---|
| Polling | Client asks on an interval | Rare updates, simplest to build |
| Long polling | Server holds the request until there’s data | Legacy environments without SSE or WebSockets |
| Server-sent events | Server to client over HTTP | Feeds, notifications, streaming AI responses |
| WebSockets | Both ways | Chat, collaboration, multiplayer, live cursors |
Whatever you pick, handle reconnection with backoff, missed messages, and duplicate delivery. Deep dive: How to stream LLM responses in the browser
304. How do you cache data on the client?
Separate server state (data owned by the backend: cached, can go stale) from client state (UI state the browser owns). For server state, use stale-while-revalidate: show cached data immediately, refetch in the background, and dedupe identical requests. Invalidate on mutations, and decide per query how stale is acceptable. Libraries like TanStack Query implement this so you don’t reinvent it.
Deep dive: Server state vs client state
305. When would you not use a framework?
For mostly static content with small islands of interactivity (marketing pages, docs, embeddable widgets), plain JavaScript or Web Components ship far less code. Frameworks pay off when UI state is complex and changes often. The senior answer weighs bundle size, team familiarity, hiring, and how long the code will live, rather than defaulting to one tool.
306. How do you approach internationalization in a JavaScript app?
Keep all user-facing strings in message files keyed by ID, use an ICU message format for plurals and gender ({count, plural, one {# item} other {# items}}), and format numbers, dates, currencies, and lists with Intl instead of string concatenation. Design layouts for text that gets much longer in other languages, support right-to-left layouts with logical CSS properties, and load locale data lazily.
307. How do you scale a website as traffic grows?
On the frontend side: serve static assets from a CDN with long cache lifetimes and hashed filenames, cache HTML at the edge where possible, keep bundles small, and avoid client-side request waterfalls. On the backend: horizontal scaling, caching layers, and database read replicas. Measure where the bottleneck actually is before adding infrastructure.
Deep dive: Essential strategies for scaling a website
308. What do you look for when reviewing JavaScript code?
Correctness first: edge cases (empty, null, very large input), unhandled promise rejections, race conditions, and listeners or timers without cleanup. Then security (unsanitized HTML, secrets in client code), then design (does this belong here, is it testable, is the naming clear), and performance only where it matters. Explain the “why” in comments so the review teaches instead of just gatekeeping.
309. How do you answer “tell me about a hard bug you fixed”?
Pick a real JavaScript bug with a clear mystery: a memory leak, a race condition, a stale closure. Walk through the situation, how you narrowed it down (reproduction, profiling, bisecting), the root cause, the fix, and what you changed so it can’t happen again (a test, a lint rule, a pattern). Give a number if you have one: heap size, error rate, INP.
Deep dive: Behavioral questions
310. How do you stay current with JavaScript?
Follow what reaches stage 3 and 4 at TC39 (the proposals repository on GitHub), read release notes for browsers and Node, check MDN and Baseline for compatibility, and try new features in small side projects before using them at work. The goal isn’t to know every proposal, but to know what’s coming so you can judge when it’s ready for production.
How to Use This List
You don’t need all 310 questions before your interview. Pick the path that matches your level:
| Level | Study first | Then |
|---|---|---|
| Junior or new grad | Fundamentals, functions and closures, arrays and strings (Q1-120) | The output questions and the first 10 coding questions |
| Mid-level | Async and the event loop, DOM and events, the coding questions (Q121-210, Q256-290) | Memory, performance, and security |
| Senior | Async, performance and security, the advanced section (Q121-155, Q211-235, Q291-310) | The coding questions under a timer, explaining out loud |
Reading answers isn’t the same as being able to produce them. For each section, close the page and explain three questions out loud, then solve the linked problems in the JavaScript coding questions editor with tests.
More ways to prepare on FrontendLead:
- Trivia questions and Quiz Yourself for rapid-fire concept review.
- 300+ React interview questions and answers for the framework round.
- The 10 JavaScript coding questions that keep showing up and the patterns behind them.
- Frontend system design questions for senior loops.
- The JavaScript chapter of the handbook and the study plans if you want a week-by-week schedule.
Related reading: How to become a frontend developer: a step-by-step roadmap · Frontend frameworks compared: React vs Vue vs Angular vs Svelte · 120+ TypeScript interview questions and answers
