← Interview prep

JavaScript interview questions

Language fundamentals, ES features, and async behavior.

200 questions · Page 2 of 10

Want the full pack? Interview packs · Mock interview · Mentora

Page 2 of 10

Questions 21–40 of 200 · 0 of 20 on this page marked learned

21.javascript-0021Hardsenior

What are generators in JavaScript, and how do they relate to the iterator protocol?

A generator is a function declared with function* that can pause at yield and be resumed later, producing values on demand. Calling it returns a generator object that follows the iterator protocol, so for...of, spread, and destructuring work with it. Generators allow lazy sequences, infinite streams, and two-way communication through next(value).

Full answer

An iterator is any object with a next() method that returns { value, done }. An iterable is an object with a [Symbol.iterator]() method that returns an iterator. for...of, spread, Array.from, and destructuring all work on iterables.

A generator function, written function*, is a shortcut for building iterators. Calling it does not run the body. It returns a generator object, which is both an iterator and an iterable. Each next() runs the body until the next yield, hands out that value, and freezes the function with all its local variables. The next call continues from the same place. When the function ends, done becomes true, and the return value is reported once.

Because values are produced on demand, a generator can describe an infinite sequence safely, as long as the consumer stops. This lazy behavior saves memory when a large list would otherwise have to be built first.

Generators are two-way. next(x) makes the paused yield expression evaluate to x. throw(error) raises an error at the pause, and return(value) ends the generator early, running any finally blocks. yield* delegates to another iterable.

Async generators (async function*) yield promises and are consumed with for await...of. They fit paginated APIs and streams.

javascript
function* idGenerator(prefix) {
  let n = 1;
  while (true) {
    yield `${prefix}-${n++}`;
  }
}

function* take(iterable, count) {
  if (count <= 0) return;
  let seen = 0;
  for (const item of iterable) {
    yield item;
    if (++seen >= count) return;
  }
}

console.log([...take(idGenerator('STU'), 3)]);

const gen = idGenerator('ROLL');
console.log(gen.next(), gen.next().value);

function* conversation() {
  const name = yield 'What is your name?';
  const city = yield `Hi ${name}, which city?`;
  return `${name} from ${city}`;
}
const chat = conversation();
console.log(chat.next().value);
console.log(chat.next('Zoya').value);
console.log(chat.next('Pune'));

const countdown = {
  from: 3,
  [Symbol.iterator]() {
    let current = this.from;
    return { next: () => (current > 0 ? { value: current--, done: false } : { value: undefined, done: true }) };
  },
};
console.log([...countdown]);

async function* pages() {
  for (let page = 1; page <= 2; page++) {
    await new Promise((resolve) => setTimeout(resolve, 5));
    yield `page ${page}`;
  }
}
(async () => {
  for await (const page of pages()) console.log(page);
})();

Run with Node.js v24.22.1 as js-21.js; two runs gave identical output. Output: [ 'STU-1', 'STU-2', 'STU-3' ] { value: 'ROLL-1', done: false } ROLL-2 What is your name? Hi Zoya, which city? { value: 'Zoya from Pune', done: true } [ 3, 2, 1 ] page 1 page 2

Key points

  • An iterator has next() returning { value, done }; an iterable has Symbol.iterator.
  • function* returns a generator object that is both.
  • yield pauses and keeps local state; next resumes.
  • Generators are lazy, so infinite sequences are possible.
  • next(value), throw, return, and yield* give two-way control; async generators work with for await.

Common mistakes

  • Spreading or looping over an infinite generator without a stop condition, which never finishes.
  • Reusing a finished generator. Once done is true, it stays done; call the function again for a new one.
  • Forgetting that the first next(value) argument is ignored, because no yield is waiting yet.
  • Using a generator when a plain array is simpler and the data is small.

Follow-ups

  • How does yield* differ from yielding each item in a loop?
  • What does return() do to a generator that is paused inside a try...finally?
  • How would you consume a paginated API with an async generator?

Tips

  • Explain iterator and iterable first. It makes the generator part simple.
  • Use an id generator or pagination as an example; both are realistic.
  • Mention laziness and memory, then mention two-way next(value) for extra depth.
22.javascript-0022Easyfresher

What is the difference between Set and Map in JavaScript, and how does Map differ from a plain object?

A Set stores unique values, and a Map stores key-value pairs where keys can be of any type. Both keep insertion order and check membership in roughly constant time. A Map is safer than a plain object for dynamic keys because it has no inherited keys, accepts object keys, and has a size property.

Full answer

A Set is a collection of unique values. Adding a value that is already present does nothing. It is the quick way to remove duplicates or to test membership with has. Equality uses the SameValueZero rule, so NaN equals NaN and 0 equals -0, but two different objects are never equal.

A Map stores pairs of key and value. Unlike an object, whose keys become strings or symbols, a Map key can be anything: a number, an object, even a function. Maps remember insertion order and expose size. They have get, set, has, delete, and clear, and they are directly iterable with for...of, yielding [key, value] pairs.

Compared with a plain object used as a dictionary, a Map has no prototype keys (so a key such as constructor is not a problem), handles frequent additions and removals well, and keeps keys of any type distinct. Objects are better for fixed records and for data that must be serialized with JSON.stringify, because Maps and Sets do not serialize by default.

WeakMap and WeakSet hold their keys weakly, so an object used as a key can still be garbage collected. They are not iterable and have no size.

javascript
const attendance = ['Asha', 'Ravi', 'Asha', 'Meera', 'Ravi'];
const unique = new Set(attendance);
console.log(unique.size, [...unique], unique.has('Ravi'));

const nanSet = new Set([NaN, NaN, 0, -0]);
console.log(nanSet.size);

const roomByStudent = new Map();
const key = { id: 1 };
roomByStudent.set('Asha', 'Room 4');
roomByStudent.set(key, 'Room 9');
roomByStudent.set(1, 'number key').set('1', 'string key');
console.log(roomByStudent.get(key), roomByStudent.get(1), roomByStudent.get('1'));
console.log(roomByStudent.size);

for (const [studentKey, room] of roomByStudent) {
  if (typeof studentKey === 'string' && studentKey !== '1') console.log(studentKey, room);
}

const plain = {};
plain[key] = 'a';
plain[{ id: 2 }] = 'b'; // both keys turn into "[object Object]"
console.log(Object.keys(plain));
console.log('constructor' in {}, new Map().has('constructor'));

console.log(JSON.stringify({ set: unique, map: roomByStudent }));
console.log(JSON.stringify([...unique]), JSON.stringify(Object.fromEntries([['a', 1]])));

Run with Node.js v24.22.1 as js-22.js; two runs gave identical output. Output: 3 [ 'Asha', 'Ravi', 'Meera' ] true 2 Room 9 number key string key 4 Asha Room 4 [ '[object Object]' ] true false {"set":{},"map":{}} ["Asha","Ravi","Meera"] {"a":1}

Key points

  • Set: unique values; Map: key-value pairs with keys of any type.
  • Both preserve insertion order and have size.
  • Equality uses SameValueZero; objects are compared by reference.
  • Map avoids inherited keys and string-only keys of plain objects.
  • Maps and Sets are not serialized by JSON.stringify without conversion.

Common mistakes

  • Using an object as a map with object keys; all keys collapse into the same string.
  • Expecting two equal-looking objects to be one entry in a Set.
  • Calling JSON.stringify on a Map or Set and getting an empty object.
  • Using a plain object for a dictionary of user-supplied keys and being hit by keys like __proto__ or constructor.

Follow-ups

  • What is the difference between Map and WeakMap, and when do you want weak keys?
  • How would you find the intersection of two arrays using Set?
  • What is the time complexity of Set.has compared with Array.includes?

Tips

  • Start with the one-line purpose of each, then give the three object-versus-Map differences.
  • Show the Set deduplication one-liner; it is the answer to many coding warm-ups.
  • State the serialization limitation; it is a practical trade-off.
23.javascript-0023Easyfresher

What is the difference between rest parameters and the spread operator? Both use three dots.

Rest gathers many values into one array, and it appears where values are received: in a function's parameter list or on the left of a destructuring pattern. Spread does the opposite and expands one collection into many values, in a call, an array literal, or an object literal. The same three dots mean gather or expand depending on position.

Full answer

The symbol ... has two meanings, and the position tells which one applies.

Rest is used where values are received. In a function definition, function total(first, ...others) collects all extra arguments into a real array named others. The rest parameter must be last, and there can be only one. It replaces the old arguments object, which is array-like, not a real array, and does not exist in arrow functions. In destructuring, const [head, ...tail] = list and const { id, ...info } = object collect the remaining items or properties.

Spread is used where values are provided. In a call, Math.max(...marks) expands an array into separate arguments. In an array literal, [...a, ...b] joins arrays. In an object literal, { ...a, ...b } merges properties.

A quick test: if the dots are on the receiving side of an assignment or in a parameter list, it is rest. If they are in an expression that produces values, it is spread.

Both create new arrays or objects, and both are shallow. Spread on arrays needs an iterable, while spread in object literals needs an object (it ignores null and undefined).

javascript
function average(label, ...scores) {
  const total = scores.reduce((sum, score) => sum + score, 0);
  return `${label}: ${total / scores.length}`;
}

console.log(average('Maths', 70, 80, 90));
const scores = [60, 75];
console.log(average('Physics', ...scores, 90));

const [winner, ...others] = ['Isha', 'Dev', 'Sam'];
console.log(winner, others);

const { id, ...profile } = { id: 9, name: 'Kabir', city: 'Delhi' };
console.log(id, profile);

function oldStyle() {
  return Array.isArray(arguments);
}
function newStyle(...args) {
  return Array.isArray(args);
}
console.log(oldStyle(1, 2), newStyle(1, 2));

console.log({ ...null, ...undefined, a: 1 });
try {
  console.log([...null]);
} catch (error) {
  console.log(error.name);
}

Run with Node.js v24.22.1 as js-23.js; two runs gave identical output. Output: Maths: 80 Physics: 75 Isha [ 'Dev', 'Sam' ] 9 { name: 'Kabir', city: 'Delhi' } false true { a: 1 } TypeError

Key points

  • Rest collects into an array or object; spread expands into separate values.
  • Rest appears in parameter lists and destructuring patterns; spread in calls and literals.
  • A rest parameter must be last and is a real array.
  • Rest replaces the arguments object, which is missing in arrow functions.
  • Both produce shallow copies.

Common mistakes

  • Putting a rest parameter anywhere except the last position, which is a SyntaxError.
  • Believing rest and spread are the same operator in the same position.
  • Using arguments inside an arrow function.
  • Spreading a huge array into a call and exceeding the argument limit.

Follow-ups

  • What does arguments contain, and why is it considered legacy?
  • Can a function have two rest parameters?
  • How does rest in object destructuring treat inherited properties?

Tips

  • Use the "receiving side versus producing side" rule; it is easy to remember and easy to explain.
  • Show one example of each in a single function.
  • Mention that rest gives a real array so map and filter are available.
24.javascript-0024Easyfresher

What is the difference between primitive and reference types in JavaScript?

Primitives (string, number, bigint, boolean, undefined, null, symbol) are immutable and copied by value. Objects, arrays, and functions are reference types: a variable holds a reference to them, so copies and function arguments share the same underlying object. JavaScript always passes arguments by value, and for objects that value is the reference.

Full answer

JavaScript has seven primitive types: string, number, bigint, boolean, undefined, null, and symbol. Everything else is an object, including arrays, functions, dates, and maps.

A primitive value cannot be changed. A method such as toUpperCase() returns a new string and leaves the original alone. Assigning a primitive to another variable copies the value, and the two variables are independent. Comparing primitives with === compares the values themselves.

An object variable holds a reference, which can be thought of as an address. Assigning it to another variable copies the address, so both names lead to the same object. A change made through one name is visible through the other. Comparing two objects with === asks whether they are the very same object, not whether their contents match.

The same idea applies to function arguments. JavaScript is pass-by-value: the function receives a copy of the variable's value. For a primitive, that is the value. For an object, it is the reference. The function can change the object's contents, but reassigning its own parameter variable does not change the caller's variable.

Frozen objects, const, and copies (spread or structuredClone) are the tools to control accidental sharing.

javascript
let a = 10;
let b = a;
b = 20;
console.log(a, b);

const text = 'java';
text.toUpperCase();
console.log(text, text.toUpperCase());

const original = { marks: 80 };
const alias = original;
alias.marks = 95;
console.log(original.marks, original === alias);
console.log({ marks: 95 } === original);

function changeContents(student) {
  student.marks = 50;
}
function reassign(student) {
  student = { marks: 0 };
  return student.marks;
}
changeContents(original);
console.log(original.marks);
console.log(reassign(original), original.marks);

const copy = { ...original };
copy.marks = 1;
console.log(original.marks, copy.marks);
console.log(typeof 42n, typeof Symbol('id'), typeof null, typeof (() => {}));

Run with Node.js v24.22.1 as js-24.js; two runs gave identical output. Output: 10 20 java JAVA 95 true false 50 0 50 50 1 bigint symbol object function

Key points

  • Seven primitives; everything else is an object.
  • Primitives are immutable and copied by value.
  • Objects are accessed through references; copies share the same object.
  • === on objects compares identity, not contents.
  • Arguments are passed by value; for objects the value is a reference.

Common mistakes

  • Saying objects are passed by reference. The reference itself is passed by value.
  • Assuming that copying with = makes a new object.
  • Comparing two arrays or objects with === to test whether contents are the same.
  • Thinking a string method changes the string; strings are immutable.

Follow-ups

  • What does typeof return for null, arrays, and functions?
  • How would you compare two objects by content?
  • Where do primitives and objects live in memory, stack or heap?

Tips

  • Explain with the two-variable example; it takes ten seconds and is clear.
  • Say "pass by value, where the value of an object variable is a reference". This precise phrase impresses interviewers.
  • Mention memory only if asked; engines are free to optimize where values are stored.
25.javascript-0025Hardsenior

How does prototypal inheritance work in JavaScript, and how do ES6 classes relate to it?

Every object has an internal link to a prototype object. When a property is not found on the object, the engine follows that link up the chain until it finds it or reaches null. Constructor functions and ES6 classes are different syntax over the same mechanism: methods live once on the prototype and are shared by all instances.

Full answer

In JavaScript, objects inherit directly from other objects. Each object has an internal slot called [[Prototype]], which can be read with Object.getPrototypeOf(obj). When code reads obj.speak, the engine checks obj itself first. If it is missing, it checks the prototype, then the prototype's prototype, and so on until it finds the property or reaches null and returns undefined. This is the prototype chain. Writing a property always creates it on the object itself (unless a setter is found), so assignment does not change the prototype.

There are three ways to set up a link:

  • Object.create(proto) makes a new object whose prototype is proto.
  • A constructor function called with new creates an object whose prototype is the function's prototype property. Methods are added to Constructor.prototype.
  • An ES6 class does the same with cleaner syntax. extends links the prototypes of the two classes and the constructor functions, and super calls up the chain. A class is still a function, and its methods are on Class.prototype.

Putting methods on the prototype means all instances share one copy, which saves memory compared with creating a function in every constructor call. instanceof walks the prototype chain, and Object.hasOwn tests only the object itself.

Classes add real differences: they are not hoisted for use, always run in strict mode, require new, and support private #fields. Modifying Object.prototype or built-in prototypes is considered unsafe.

javascript
const animal = {
  describe() {
    return `${this.name} makes ${this.sound()}`;
  },
  sound() {
    return 'a sound';
  },
};
const dog = Object.create(animal);
dog.name = 'Bruno';
dog.sound = () => 'a bark';
console.log(dog.describe());
console.log(Object.getPrototypeOf(dog) === animal, Object.hasOwn(dog, 'describe'));

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function () {
  return `Hello, I am ${this.name}`;
};
const p1 = new Person('Anu');
const p2 = new Person('Vik');
console.log(p1.greet(), p1.greet === p2.greet);

class Employee extends Person {
  #salary;
  constructor(name, salary) {
    super(name);
    this.#salary = salary;
  }
  greet() {
    return `${super.greet()}, I work here`;
  }
  get band() {
    return this.#salary > 50000 ? 'senior' : 'junior';
  }
}
const e = new Employee('Ravi', 60000);
console.log(e.greet(), e.band);
console.log(e instanceof Employee, e instanceof Person, e instanceof Object);
console.log(typeof Employee, Object.getPrototypeOf(Employee) === Person);
console.log(Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e))) === Object.prototype);

p1.greet = () => 'shadowed';
console.log(p1.greet(), p2.greet());
try {
  Employee();
} catch (error) {
  console.log(error.name);
}

Run with Node.js v24.22.1 as js-25.js; two runs gave identical output. Output: Bruno makes a bark true false Hello, I am Anu true Hello, I am Ravi, I work here senior true true true function true true shadowed Hello, I am Vik TypeError

Key points

  • Property lookup follows the [[Prototype]] chain until null.
  • Assignment creates an own property; it does not change the prototype.
  • Object.create, constructor functions with new, and classes all build prototype links.
  • Methods on the prototype are shared by all instances.
  • Classes are syntax over prototypes, with extra rules such as strict mode and private fields.

Common mistakes

  • Saying classes replaced prototypes. They are built on them.
  • Defining methods inside a constructor and creating one copy per instance.
  • Assigning to an inherited property and expecting the prototype to change.
  • Replacing Constructor.prototype with a new object and forgetting to restore the constructor property.

Follow-ups

  • What is the difference between __proto__ and prototype?
  • How does super work in an object literal method or in a static method?
  • What happens to the chain when you use Object.create(null)?

Tips

  • Draw the chain: instance, then Class.prototype, then Object.prototype, then null. A sketch makes the answer concrete.
  • Show that methods are shared with the p1.greet === p2.greet check.
  • Mention private fields as the main thing classes give that plain prototypes do not.
26.javascript-0026Easyfresher

What is type coercion in JavaScript? Why does "5" + 3 give "53" but "5" - 3 give 2?

Type coercion is the automatic or manual conversion of a value from one type to another. The + operator joins text if either side is a string, while -, *, and / always convert both sides to numbers. Explicit conversion with Number(), String(), and Boolean() is clearer and safer than relying on implicit coercion.

Full answer

JavaScript has no type declarations, so operators must decide what to do when the two sides are of different types. Converting a value to the type an operation needs is called coercion. It is implicit when the engine does it for you, and explicit when you call Number(x), String(x), or Boolean(x) yourself.

The + operator has two jobs: addition and joining text. If either operand is a string after converting objects to primitives, the result is a string, so "5" + 3 becomes "53". The operators -, *, /, and % have only one job, arithmetic, so they convert both sides to numbers. "5" - 3 is 2.

Number conversion rules that appear often: an empty or whitespace-only string becomes 0; a string with letters becomes NaN; true becomes 1, false becomes 0; null becomes 0; undefined becomes NaN. String conversion of an array joins its items with commas, and an object becomes [object Object]. For objects, the engine calls Symbol.toPrimitive, then valueOf, then toString.

Unary + is a short way to convert to a number. parseInt and parseFloat read as much of a string as they can and ignore the rest, while Number is strict and returns NaN for any extra text. parseInt should be given a radix, as in parseInt(text, 10).

In practice, convert explicitly at the boundary where input arrives, such as form fields, which always give strings.

javascript
console.log('5' + 3, '5' - 3, '5' * '2');
console.log(1 + 2 + '3', '1' + 2 + 3);
console.log(Number(''), Number('  42  '), Number('12px'), Number(null), Number(undefined), Number(true));
console.log(parseInt('12px', 10), parseFloat('3.5kg'), parseInt('abc', 10));
console.log(+'7', +'', -'3');
console.log(String([1, 2, 3]), String({}), String(null), String(undefined));
console.log([] + [], [] + {}, [1] * 2);

const price = {
  valueOf() {
    return 100;
  },
  toString() {
    return 'hundred';
  },
};
console.log(price + 1, `${price}`, price * 2);

const fieldValue = '25'; // form fields always give strings
console.log(fieldValue + 5, Number(fieldValue) + 5);

Run with Node.js v24.22.1 as js-26.js; two runs gave identical output. Output: 53 2 10 33 123 0 42 NaN 0 NaN 1 12 3.5 NaN 7 0 -3 1,2,3 [object Object] null undefined [object Object] 2 101 hundred 200 255 30

Key points

  • + joins text if either operand is a string; other arithmetic operators convert to numbers.
  • Number("") is 0, Number("abc") is NaN, Number(null) is 0, Number(undefined) is NaN.
  • Objects are converted using toPrimitive, valueOf, and toString.
  • parseInt reads a leading number; Number rejects extra characters.
  • Convert input explicitly rather than depending on implicit rules.

Common mistakes

  • Adding two numbers read from a form field and getting joined text.
  • Using parseInt without a radix or on values that are not strings, such as parseInt(0.0000005), which gives 5.
  • Assuming Number("12px") returns 12.
  • Trusting == and + with mixed types in business logic instead of converting explicitly.

Follow-ups

  • What is the output of [] + {} and {} + [] in the console, and why does the second sometimes differ?
  • How does Symbol.toPrimitive change coercion for an object?
  • What is the difference between Number(x), parseInt(x), and unary plus?

Tips

  • Explain with the one-sentence rule for + first, then the rule for other operators.
  • Show an explicit conversion at an input boundary as the professional habit.
  • If asked about [] + {}, do it step by step: both become strings, then join.
27.javascript-0027Easyfresher

What are truthy and falsy values in JavaScript, and what are the common traps?

When a value is used in a condition, JavaScript converts it to a boolean. Exactly eight values are falsy: false, 0, -0, 0n, an empty string, null, undefined, and NaN. Everything else is truthy, including empty arrays, empty objects, and the string "0".

Full answer

In an if, a while, a ternary, or an operand of !, &&, and ||, the value does not have to be a boolean. The engine converts it with the same rules as Boolean(value). The falsy values are a short fixed list: false, 0, -0, 0n (the zero BigInt), "" (empty string), null, undefined, and NaN. The rare object document.all in browsers is also falsy for historical reasons. All other values are truthy.

Traps come from values that look empty. An empty array [], an empty object {}, the string "0", the string "false", and an instance of new Boolean(false) are all truthy. Another trap is using a truthiness check for numbers: if (count) treats a valid 0 as missing.

The operators && and || do not return booleans. They return one of their operands. a || b returns a if it is truthy, otherwise b. a && b returns a if it is falsy, otherwise b. This is used for defaults and guards. When 0 or "" are valid values, use ??, which falls back only for null and undefined.

!!value is a short way to convert to a boolean, and Boolean(value) says the same thing more clearly.

javascript
const values = [false, 0, -0, 0n, '', null, undefined, NaN, [], {}, '0', 'false', ' ', -1, Infinity];
for (const value of values) {
  console.log(String(typeof value).padEnd(9), JSON.stringify(String(value)).padEnd(12), Boolean(value));
}

const quantity = 0;
console.log(quantity || 10, quantity ?? 10);
const name = '';
console.log(name || 'guest', name ?? 'guest');

const user = { profile: null };
console.log(user.profile && user.profile.name);
console.log(1 && 'second', 0 && 'second', null || 'fallback', 'first' || 'fallback');

const items = [];
console.log(items ? 'array exists' : 'no array', items.length ? 'has items' : 'empty');

Run with Node.js v24.22.1 as js-27.js; two runs gave identical output. Output: boolean "false" false number "0" false number "0" false bigint "0" false string "" false object "null" false undefined "undefined" false number "NaN" false object "" true object "[object Object]" true string "0" true string "false" true string " " true number "-1" true number "Infinity" true 10 0 guest null second 0 fallback first array exists empty

Key points

  • Falsy values: false, 0, -0, 0n, "", null, undefined, NaN.
  • Everything else is truthy, including [], {}, "0", and "false".
  • && and || return operands, not booleans.
  • || treats 0 and "" as missing; ?? only treats null and undefined as missing.
  • Use Boolean(value) or !!value to get a real boolean.

Common mistakes

  • Writing if (count) when 0 is a valid count.
  • Thinking an empty array is falsy and checking it without .length.
  • Treating the string "false" or "0" as falsy.
  • Using || for a default when 0, false, or an empty string are meaningful values.

Follow-ups

  • What does a && b || c return, and why is a ternary sometimes clearer?
  • How does optional chaining combine with ??
  • Why is [] == false true when [] itself is truthy?

Tips

  • Memorize the eight falsy values; they are the whole answer.
  • Mention the empty array and the "0" string as traps.
  • Show ?? as the fix for the default-value bug with 0.
28.javascript-0028Easyfresher

What is the difference between a function declaration and a function expression? What does it mean that functions are first-class?

A declaration (function name() {}) is hoisted with its body, so it can be called before it appears. A function expression creates a function as a value, is not available before its line, and can be anonymous, named, or immediately invoked. Functions are first-class values: they can be stored in variables, passed as arguments, and returned.

Full answer

A function declaration starts a statement with the function keyword and a name. Because it is hoisted with its body, a call placed above it in the file works.

A function expression is a function used where a value is expected, for example on the right side of const add = function (a, b) { ... }, as an argument, or after return. The variable that holds it follows normal rules for let, const, or var, so calling it early fails. A named function expression, such as const fact = function inner(n) {...}, makes the name inner visible only inside the function, which helps recursion and stack traces. Arrow functions are always expressions.

An immediately invoked function expression (IIFE), (function () { ... })(), runs once and keeps its variables private. Before modules and let, this was the main way to avoid globals.

Functions are first-class: they behave like any other value. They can be put in arrays and objects, passed to other functions (callbacks), and returned from functions (closures and factories). Functions that take or return functions are called higher-order functions, and map, filter, and addEventListener are examples.

Function declarations inside blocks have confusing legacy rules in sloppy mode, so most guides advise using expressions or arrow functions for functions in blocks.

javascript
console.log(declared(2, 3));
function declared(a, b) {
  return a + b;
}

try {
  console.log(expressed(2, 3));
} catch (error) {
  console.log('expression called early:', error.name);
}
const expressed = function (a, b) {
  return a * b;
};
console.log(expressed(2, 3));

const factorial = function inner(n) {
  return n <= 1 ? 1 : n * inner(n - 1);
};
console.log(factorial(5), typeof inner);

const result = (function () {
  const secret = 'private';
  return `IIFE keeps ${secret}`;
})();
console.log(result);

function applyTwice(fn, value) {
  return fn(fn(value));
}
const addTax = (price) => price * 1.1;
console.log(applyTwice(addTax, 100).toFixed(2));

function makeMultiplier(factor) {
  return (n) => n * factor;
}
const double = makeMultiplier(2);
console.log(double(21), [1, 2, 3].map(double));

Run with Node.js v24.22.1 as js-28.js; two runs gave identical output. Output: 5 expression called early: ReferenceError 6 120 undefined IIFE keeps private 121.00 42 [ 2, 4, 6 ]

Key points

  • Declarations are hoisted with their body; expressions are not.
  • A function expression is a value and can be anonymous, named, or immediately invoked.
  • A name in a named function expression is visible only inside the function.
  • Functions are first-class: store, pass, and return them.
  • Higher-order functions accept or return functions.

Common mistakes

  • Calling a function expression before its definition.
  • Forgetting the parentheses around an IIFE, which makes the engine treat it as a declaration and fail.
  • Saying first-class functions are only about callbacks. Returning functions matters equally.
  • Declaring functions inside if blocks in sloppy mode and relying on inconsistent hoisting.

Follow-ups

  • Why does typeof inner print undefined outside the named function expression?
  • What is a higher-order function? Give two built-in examples.
  • Are modules and let/const a replacement for the IIFE pattern?

Tips

  • Start with hoisting; it is the difference interviewers listen for.
  • Explain first-class with three verbs: store, pass, return.
  • Give the IIFE as a historical pattern and say what replaced it.
29.javascript-0029Easyfresher

Why does 0.1 + 0.2 not equal 0.3 in JavaScript, and how do you handle decimals safely?

JavaScript numbers are 64-bit binary floating-point values, and many decimal fractions such as 0.1 cannot be stored exactly in binary. The tiny stored errors show up in sums like 0.1 + 0.2. Compare with a tolerance, or avoid the problem by working in whole units, such as paise or cents, and use BigInt for integers beyond the safe range.

Full answer

All numbers in JavaScript, except BigInt, use the IEEE 754 double-precision format. It stores a value in binary. Just as one third cannot be written exactly in decimal (0.3333...), one tenth cannot be written exactly in binary. The stored value for 0.1 is slightly off, and so is the one for 0.2. Adding them gives 0.30000000000000004, which is a different double than the one stored for 0.3.

This is not a JavaScript bug. Python, Java, C, and most other languages give the same result for doubles.

The safe approaches depend on the job:

  • For comparisons, test whether the difference is smaller than a tolerance, such as Math.abs(a - b) < Number.EPSILON, scaled if the numbers are large.
  • For money, store whole minor units (paise or cents) as integers and convert only for display.
  • For display, toFixed(2) returns a string rounded to two decimals; remember it returns text and that rounding is applied to the binary value.
  • For very large whole numbers, integers are exact only up to Number.MAX_SAFE_INTEGER (2^53 - 1). Beyond that, use BigInt, written with an n suffix, which cannot be mixed with normal numbers in arithmetic.
  • For precise decimal math, use a decimal library.

Number.isInteger and Number.isSafeInteger help validate input.

javascript
console.log(0.1 + 0.2, 0.1 + 0.2 === 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);

const priceInPaise = 1999;
const quantity = 3;
const totalInPaise = priceInPaise * quantity;
console.log(`Total: Rs ${(totalInPaise / 100).toFixed(2)}`);

console.log(typeof (0.5).toFixed(2), (1.005).toFixed(2), (1.255).toFixed(2));

console.log(Number.MAX_SAFE_INTEGER, 9007199254740992 === 9007199254740993);
console.log(9007199254740993n, 2n ** 64n);
try {
  console.log(1n + 1);
} catch (error) {
  console.log(error.name);
}
console.log(Number.isInteger(5.0), Number.isSafeInteger(2 ** 53));

Run with Node.js v24.22.1 as js-29.js; two runs gave identical output. Output: 0.30000000000000004 false true Total: Rs 59.97 string 1.00 1.25 9007199254740991 true 9007199254740993n 18446744073709551616n TypeError true false

Key points

  • Numbers are 64-bit binary doubles; many decimals cannot be stored exactly.
  • 0.1 + 0.2 is 0.30000000000000004 in many languages, not only in JavaScript.
  • Compare with a tolerance, not with ===.
  • Use integer minor units for money.
  • Integers are safe up to 2^53 - 1; use BigInt beyond that.

Common mistakes

  • Comparing computed decimals with ===.
  • Storing money as floating-point rupees or dollars.
  • Treating toFixed as returning a number, or expecting it to round like decimal arithmetic on 1.005.
  • Using Number for IDs larger than 2^53 and losing digits, for example 64-bit database IDs from an API.

Follow-ups

  • Why is Number.EPSILON a poor tolerance for large values, and what would you use instead?
  • How do you send a BigInt in JSON?
  • What does Math.round(2.5) return compared with Math.round(-2.5)?

Tips

  • State clearly that this is a property of binary floating point, not a JavaScript bug.
  • Offer the money rule (integer minor units) because it shows practical knowledge.
  • Mention MAX_SAFE_INTEGER and BigInt to extend the answer.
30.javascript-0030Mediummid

What are event bubbling and capturing in the DOM, and how does event delegation use them?

When a DOM event fires, it travels down from the window to the target (capturing), then runs on the target, then travels back up through the ancestors (bubbling). Listeners run during bubbling by default. Event delegation puts one listener on a parent and uses event.target to handle events from many children, including children added later.

Full answer

A click on a button inside a list is also a click on the list item, the list, the body, and the document. The browser sends the event along that path in three phases. In the capturing phase it goes from the outside in to the target's parent. At the target it runs the listeners on the element itself. In the bubbling phase it goes back out, from the parent to the window.

addEventListener(type, handler) registers for the bubbling phase. Passing true or { capture: true } registers for capturing. event.target is the element that started the event, and event.currentTarget is the element whose listener is running now. stopPropagation() stops the event from reaching later elements on the path, and stopImmediatePropagation() also stops other listeners on the same element. preventDefault() is unrelated: it cancels the browser's default action, such as following a link.

Event delegation uses bubbling. Instead of adding a listener to each of 500 rows, one listener is added to the table. Inside it, event.target.closest('tr') finds the row that was clicked. This uses less memory, and rows added later work without extra code. Delegation does not work for events that do not bubble, such as focus, blur, and mouseenter. Use focusin, focusout, or capture for those.

javascript
document.body.innerHTML = '<ul id="list"><li data-id="1">Notes <button>Delete</button></li></ul>';
const list = document.getElementById('list');
const log = [];

list.addEventListener('click', () => log.push('list capture'), { capture: true });
list.addEventListener('click', (event) => {
  log.push('list bubble');
  const button = event.target.closest('button');
  if (button && list.contains(button)) {
    log.push(`delete requested for item ${button.closest('li').dataset.id}`);
  }
});
document.body.addEventListener('click', () => log.push('body bubble'));

list.querySelector('button').addEventListener('click', (event) => {
  log.push('button target, currentTarget is ' + event.currentTarget.tagName);
});

list.querySelector('button').click();
console.log(log);

const newItem = document.createElement('li');
newItem.dataset.id = '2';
newItem.innerHTML = 'Report <button>Delete</button>';
list.appendChild(newItem);
log.length = 0;
newItem.querySelector('button').click();
console.log(log);

const stopper = document.createElement('div');
stopper.innerHTML = '<span></span>';
document.body.appendChild(stopper);
const hits = [];
stopper.addEventListener('click', () => hits.push('div'));
stopper.firstChild.addEventListener('click', (event) => {
  event.stopPropagation();
  hits.push('span');
});
stopper.firstChild.dispatchEvent(new Event('click', { bubbles: true }));
console.log(hits);

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: [ 'list capture', 'button target, currentTarget is BUTTON', 'list bubble', 'delete requested for item 1', 'body bubble' ] [ 'list capture', 'list bubble', 'delete requested for item 2', 'body bubble' ] [ 'span' ]

Key points

  • Event path: capture down, target, bubble up.
  • Listeners run in the bubbling phase unless capture is enabled.
  • target is where it started; currentTarget is where the running listener is attached.
  • Delegation: one parent listener plus closest() handles many children, including future ones.
  • focus and blur do not bubble; use focusin and focusout.

Common mistakes

  • Believing the target phase and the bubbling phase are the same thing.
  • Using event.target directly when the clicked element can be a child of the intended one, such as an icon inside a button. Use closest().
  • Calling stopPropagation everywhere, which breaks analytics and other delegated listeners.
  • Using delegation for focus or blur, which do not bubble.

Follow-ups

  • What is the difference between event.target and event.currentTarget?
  • How do passive listeners and the once option change addEventListener?
  • Which events do not bubble, and how would you delegate them?

Tips

  • Draw the three phases as an arrow going down and back up; interviewers often ask for a diagram.
  • Always mention closest() in the delegation answer, since a click often lands on a child element.
  • Name one real benefit: one listener for a long table, and dynamic rows work automatically.
31.javascript-0031Mediummid

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

Debounce waits until calls stop for a given time and then runs once, which suits search boxes and resize handlers. Throttle runs at most once per time interval no matter how often it is called, which suits scroll and drag handlers. Both are built from closures that remember a timer or a last-run time.

Full answer

Both techniques limit how often a function runs when an event fires many times in a short period.

Debounce delays execution until there has been a quiet period. Every new call cancels the previous timer and starts a new one. If a user types five letters quickly, a debounced search with a 300 ms wait fires once, 300 ms after the last key. Use it when only the final value matters: search suggestions, form validation, auto-save, and window resize.

Throttle guarantees a steady maximum rate. The function runs at the first call, and further calls are ignored until the interval has passed. During a long scroll, a throttled handler with a 100 ms limit runs about ten times per second, not hundreds of times. Use it when intermediate results matter: scroll position, mouse move, and drag.

A debounce can use a leading option to run at the first call instead of the last, and many implementations add cancel and flush methods. A throttle can also run a trailing call so the final state is not missed.

Both rely on closures. The returned wrapper keeps a timer id or a timestamp in the outer function's scope. It must forward this and the arguments to the real function. For timing, throttle uses a clock. Accepting the clock as a parameter makes it easy to test without waiting.

javascript
function debounce(fn, wait) {
  let timerId;
  return function (...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => fn.apply(this, args), wait);
  };
}

function throttle(fn, interval, now = Date.now) {
  let lastRun = -Infinity;
  return function (...args) {
    const current = now();
    if (current - lastRun >= interval) {
      lastRun = current;
      return fn.apply(this, args);
    }
  };
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

(async () => {
  const search = debounce((text) => console.log('debounced search for:', text), 60);
  for (const text of ['j', 'ja', 'jav', 'java']) {
    search(text);
    await sleep(15);
  }
  await sleep(120);

  let clock = 0;
  const onScroll = throttle((position) => console.log('throttled at', position), 50, () => clock);
  for (clock = 0; clock <= 120; clock += 10) {
    onScroll(clock);
  }
})();

Run with Node.js v24.22.1 as js-31.js; two runs gave identical output. Output: debounced search for: java throttled at 0 throttled at 50 throttled at 100

Key points

  • Debounce: run once after calls stop for the wait time.
  • Throttle: run at most once per interval.
  • Debounce suits final-value cases; throttle suits continuous events.
  • Both use closures to hold a timer id or last-run time.
  • Forward this and arguments; consider cancel, leading, and trailing options.

Common mistakes

  • Creating a new debounced function on every render or event, so each call has its own timer and nothing is limited.
  • Losing this or arguments by calling fn() instead of fn.apply(this, args).
  • Using debounce for scroll-position tracking, which only reports after the user stops.
  • Forgetting to cancel pending debounced calls when a component or page is removed.

Follow-ups

  • How would you add leading and trailing options to debounce?
  • Which browser APIs reduce the need for throttle, such as IntersectionObserver or requestAnimationFrame?
  • How would you test a debounced function without waiting for real time?

Tips

  • Use the words "wait until calls stop" for debounce and "at most once per interval" for throttle; they are the two sentences interviewers want.
  • Give a concrete case for each: search box and scroll handler.
  • When coding, write the wrapper as a normal function, not an arrow, so this can be forwarded.
32.javascript-0032Mediummid

What is currying, and how is it different from partial application? Show how to write a curry function and a compose function.

Currying turns a function of several arguments into a chain of functions that each take one argument. Partial application fixes some arguments of a function now and returns a function that takes the rest later. Compose joins functions so the output of one becomes the input of the next, and currying makes small functions fit together for it.

Full answer

Currying changes the shape of a function. add(a, b, c) becomes add(a)(b)(c). Each call returns a function that waits for the next argument until all have arrived. The idea comes from functional programming, where small functions with one input are easy to combine.

Partial application is related but different. It fixes a few arguments and returns a function for the rest, whatever count remains. Function.prototype.bind does this, and so does const addTax = (rate) => (price) => price * (1 + rate).

A flexible curry helper reads the function's length, which is the number of declared parameters. The wrapper collects arguments across calls and runs the original function as soon as enough arguments have been gathered. Functions with default or rest parameters have a smaller length, so they need an explicit arity.

Compose and pipe join single-argument functions. compose(f, g)(x) is f(g(x)), running right to left, while pipe(f, g)(x) is g(f(x)), running left to right. Both can be written with reduce. Currying helps because a curried function with the data last, such as filterBy(minimum)(list), can be partly applied and dropped into a pipe.

Currying costs a small amount of call overhead and can make stack traces longer, so use it where it improves reuse.

javascript
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 compose = (...fns) => (input) => fns.reduceRight((value, fn) => fn(value), input);
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);

const add3 = curry((a, b, c) => a + b + c);
console.log(add3(1)(2)(3), add3(1, 2)(3), add3(1)(2, 3));

const multiplyBy = curry((factor, value) => factor * value);
const double = multiplyBy(2);
console.log([1, 2, 3].map(double));

const greet = function (greeting, name) {
  return `${greeting}, ${name}`;
};
const hello = greet.bind(null, 'Hello'); // partial application with bind
console.log(hello('Ria'));

const filterBy = curry((minimum, list) => list.filter((n) => n >= minimum));
const total = (list) => list.reduce((sum, n) => sum + n, 0);
const passMarkTotal = pipe(filterBy(40), total);
console.log(passMarkTotal([35, 52, 40, 91, 12]));

const exclaim = (text) => text + '!';
const wrap = (text) => `[${text}]`;
console.log(compose(wrap, exclaim)('hi'), pipe(wrap, exclaim)('hi'));
console.log(greet.length, ((a, b = 2) => a + b).length);

Run with Node.js v24.22.1 as js-32.js; two runs gave identical output. Output: 6 6 6 [ 2, 4, 6 ] Hello, Ria 183 [hi!] [hi]! 2 1

Key points

  • Currying: f(a, b, c) becomes f(a)(b)(c).
  • Partial application: fix some arguments now, supply the rest later.
  • A curry helper uses fn.length to know when to run.
  • compose runs right to left; pipe runs left to right; both use reduce.
  • Put the data argument last so functions can be partly applied.

Common mistakes

  • Using fn.length with default or rest parameters and curry never running as expected.
  • Mixing up compose and pipe order.
  • Calling the final curried function with extra arguments and assuming they are ignored; the helper passes them to the original function.
  • Putting the data argument first, which makes partial application less useful.

Follow-ups

  • How would you write curry for a function with a variable number of arguments?
  • How is a partially applied function different from a closure that captures a variable?
  • How would you handle async functions in a pipe?

Tips

  • Define the difference in one sentence each before writing code.
  • Mention the data-last convention; it shows you know why currying is used.
  • Explain fn.length and its limits unprompted.
33.javascript-0033Mediummid

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

Promise.all fulfills with every result or rejects at the first rejection. Promise.allSettled waits for all and reports each outcome without rejecting. Promise.race settles as soon as the first promise settles, either way. Promise.any fulfills with the first fulfillment and rejects with an AggregateError only if all of them reject.

Full answer

All four take an iterable of promises and return one promise, and they differ in when and how that promise settles.

Promise.all is all-or-nothing. If every input fulfills, the result is an array of values in input order (not completion order). If any input rejects, the result rejects immediately with that reason. The remaining promises keep running, but their results are ignored. Use it when every result is required.

Promise.allSettled never rejects. It waits for every input and returns an array of objects, each either { status: 'fulfilled', value } or { status: 'rejected', reason }. Use it when you want to report partial success, such as loading several widgets on a page.

Promise.race follows whichever promise settles first, whether it fulfills or rejects. The classic use is a timeout: race the real request against a promise that rejects after some milliseconds.

Promise.any follows the first fulfillment and ignores rejections until all have failed. Then it rejects with an AggregateError, whose errors property lists the reasons. Use it to try several mirrors of a resource and take the quickest success.

Non-promise values in the list are treated as already fulfilled. An empty list gives a fulfilled all and allSettled, a forever-pending race, and a rejected any.

javascript
const task = (ms, value, fail = false) =>
  new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));

(async () => {
  console.log(await Promise.all([task(30, 'slow'), task(10, 'fast'), 'plain value']));

  try {
    await Promise.all([task(10, 'a'), task(20, 'b failed', true)]);
  } catch (error) {
    console.log('all rejected with:', error.message);
  }

  const settled = await Promise.allSettled([task(10, 'ok'), task(20, 'bad', true)]);
  console.log(settled.map((r) => (r.status === 'fulfilled' ? r.value : r.reason.message)));

  console.log(await Promise.race([task(30, 'slow winner'), task(10, 'fast winner')]));
  try {
    await Promise.race([task(30, 'late'), task(10, 'early failure', true)]);
  } catch (error) {
    console.log('race rejected with:', error.message);
  }

  console.log(await Promise.any([task(10, 'mirror 1 down', true), task(30, 'mirror 2 ok')]));
  try {
    await Promise.any([task(10, 'x', true), task(20, 'y', true)]);
  } catch (error) {
    console.log(error.name, error.errors.map((e) => e.message));
  }

  const timeout = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms));
  try {
    await Promise.race([task(100, 'too slow'), timeout(20)]);
  } catch (error) {
    console.log('guarded call:', error.message);
  }
})();

Run with Node.js v24.22.1 as js-33.js; two runs gave identical output. Output: [ 'slow', 'fast', 'plain value' ] all rejected with: b failed [ 'ok', 'bad' ] fast winner race rejected with: early failure mirror 2 ok AggregateError [ 'x', 'y' ] guarded call: timeout

Key points

  • all: every result in input order, or the first rejection.
  • allSettled: waits for all and never rejects; reports status for each.
  • race: first to settle wins, success or failure.
  • any: first success wins; AggregateError if all fail.
  • Rejection in all or race does not cancel the other promises.

Common mistakes

  • Using Promise.all when partial results are acceptable, so one failure hides the other data.
  • Assuming a rejected Promise.all cancels the other tasks; they continue and may still cause side effects.
  • Expecting results of all in completion order instead of input order.
  • Using Promise.race for a timeout and forgetting to clear the timer afterwards, which keeps the process alive.

Follow-ups

  • How would you limit how many promises run at the same time?
  • How can you cancel the slow request when a race is lost?
  • What does Promise.all do with an empty array?

Tips

  • Give one sentence on each method, then a use case: required data, partial success, timeout, fastest mirror.
  • Mention that none of them cancel work; AbortController does that.
  • Use a table in your head: waits for all or first, and how failures are handled.
34.javascript-0034Mediummid

How does error handling work in JavaScript? Cover try/catch/finally, custom errors, error.cause, and async errors.

try/catch/finally handles thrown values synchronously, and a finally block always runs. Custom errors extend Error so they carry a name, a message, a stack, and extra fields, and error.cause chains the original failure. In async code, a rejected promise must be caught with .catch or try/catch around await; an outer try/catch does not catch an un-awaited promise.

Full answer

Any value can be thrown, but throwing Error objects is the standard because they carry a message, a name, and a stack. A try block runs code. If something throws, control jumps to catch. The finally block runs in every case, including after a return, and it is the right place to release resources. A return inside finally overrides earlier returns and swallows errors, so it is best avoided.

Custom error classes extend Error so code can tell failure types apart with instanceof and so they can carry fields such as an HTTP status code. Call super(message) and set this.name. The cause option, new Error('message', { cause: original }), links the lower-level error that triggered this one, so wrapping an error keeps the full story.

Catch only what the code can handle. After checking the type, re-throw unknown errors, because hiding them makes bugs hard to find.

Async code adds a rule: a rejection is not a thrown exception in the current call stack. await converts a rejection into a throw at that line, so try/catch works around await. A promise that is not awaited or returned escapes the surrounding try/catch, and if nobody handles it, the runtime reports an unhandled rejection (Node.js exits with an error by default, and browsers fire an unhandledrejection event).

Global handlers (window.onerror, unhandledrejection, process.on('uncaughtException')) are for logging, not for continuing normally.

javascript
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

function parseMarks(text) {
  try {
    const marks = JSON.parse(text);
    if (marks < 0 || marks > 100) throw new ValidationError('Marks out of range', 'marks');
    return marks;
  } catch (error) {
    if (error instanceof ValidationError) throw error;
    throw new Error('Could not read marks', { cause: error });
  } finally {
    console.log('parse attempted for', JSON.stringify(text));
  }
}

for (const input of ['85', '150', 'abc']) {
  try {
    console.log('result:', parseMarks(input));
  } catch (error) {
    console.log(error.name, '-', error.message, error.field ?? '', error.cause?.name ?? '');
  }
}

function returnsFromTry() {
  try {
    return 'from try';
  } finally {
    console.log('finally runs before the return completes');
  }
}
console.log(returnsFromTry());

const failLater = () => new Promise((_, reject) => setTimeout(() => reject(new Error('async failure')), 10));

(async () => {
  try {
    failLater(); // not awaited: the catch below cannot see it
    console.log('try block finished normally');
  } catch (error) {
    console.log('never printed');
  }
  try {
    await new Promise((resolve) => setTimeout(resolve, 30));
    await failLater();
  } catch (error) {
    console.log('caught with await:', error.message);
  }
})();
process.on('unhandledRejection', (reason) => console.log('unhandled rejection:', reason.message));

Run with Node.js v24.22.1 as js-34.js; two runs gave identical output. Output: parse attempted for "85" result: 85 parse attempted for "150" ValidationError - Marks out of range marks parse attempted for "abc" Error - Could not read marks SyntaxError finally runs before the return completes from try try block finished normally unhandled rejection: async failure caught with await: async failure

Key points

  • Throw Error objects; they carry message, name, and stack.
  • finally always runs; avoid return inside it.
  • Custom errors extend Error and support instanceof checks; use cause to chain errors.
  • Catch what you can handle and re-throw the rest.
  • An un-awaited rejected promise escapes try/catch and becomes an unhandled rejection.

Common mistakes

  • Swallowing errors with an empty catch block.
  • Throwing strings instead of Error objects, so there is no stack trace.
  • Forgetting to await or return a promise inside try, so the catch never runs.
  • Wrapping an error without cause and losing the original stack.

Follow-ups

  • What is the difference between throw in a callback and a rejection in a promise?
  • How does error handling differ between Promise.all and Promise.allSettled?
  • How would you report errors from a React or Vue component tree?

Tips

  • Show one custom error with a field, and one wrap with cause; it proves you use modern features.
  • State the re-throw rule: handle what you understand, re-throw the rest.
  • Explain why an un-awaited promise escapes the try; interviewers like this trap.
35.javascript-0035Mediummid

Why does [10, 9, 1].sort() return [1, 10, 9]? How does Array.prototype.sort work and what are its pitfalls?

Without a comparator, sort converts items to strings and compares them in UTF-16 order, so 10 comes before 9. A comparator function returning a negative, zero, or positive number gives numeric or custom ordering. sort changes the array in place, is stable in modern engines, and needs localeCompare or Intl.Collator for human-friendly text order.

Full answer

The default order of sort() is text order. Every item is converted to a string, and strings are compared character by character using UTF-16 code unit values. The string "10" starts with "1", which comes before "9", so 10 lands before 9. Items that are undefined are always placed at the end without calling the comparator.

To sort numbers, pass a comparator: (a, b) => a - b for ascending, (a, b) => b - a for descending. The comparator returns a negative number if a goes first, a positive number if b goes first, and zero if they are equal. Returning a boolean such as a > b is a bug, because true and false become 1 and 0 and never negative.

sort mutates the array and returns the same array. Copy first with [...list].sort(...), or use toSorted (ES2023), which returns a new array. Since ES2019, sort must be stable, so items that compare equal keep their original relative order. This makes it safe to sort by several keys in separate passes, from the least important key to the most important.

For text shown to people, plain code unit order puts uppercase letters before lowercase ones and accented letters after z. Use a.localeCompare(b) or new Intl.Collator('en').compare instead. For large lists, a collator object is faster because it is created once.

A comparator must be consistent. Random comparators such as () => Math.random() - 0.5 produce a biased shuffle.

javascript
console.log([10, 9, 1].sort());
console.log([10, 9, 1].sort((a, b) => a - b));
console.log([10, 9, 1].sort((a, b) => b - a));
console.log([3, 1, 2].sort((a, b) => a > b)); // boolean comparator: wrong, see the notes
console.log([3, undefined, 1].sort((a, b) => a - b));

const names = ['zara', 'Anil', 'émile', 'Bina', 'emma'];
console.log([...names].sort());
console.log([...names].sort((a, b) => a.localeCompare(b, 'en')));
console.log([...names].sort(new Intl.Collator('en', { sensitivity: 'base' }).compare));

const students = [
  { name: 'Asha', grade: 'B' },
  { name: 'Ravi', grade: 'A' },
  { name: 'Meera', grade: 'B' },
  { name: 'Dev', grade: 'A' },
];
const byGrade = students.toSorted((x, y) => x.grade.localeCompare(y.grade));
console.log(byGrade.map((s) => s.name).join(', '));
console.log(students.map((s) => s.name).join(', '));

const list = [2, 1];
const sorted = list.sort();
console.log(sorted === list, list);

Run with Node.js v24.22.1 as js-35.js; two runs gave identical output. Output: [ 1, 10, 9 ] [ 1, 9, 10 ] [ 10, 9, 1 ] [ 3, 1, 2 ] [ 1, 3, undefined ] [ 'Anil', 'Bina', 'emma', 'zara', 'émile' ] [ 'Anil', 'Bina', 'émile', 'emma', 'zara' ] [ 'Anil', 'Bina', 'émile', 'emma', 'zara' ] Ravi, Dev, Asha, Meera Asha, Ravi, Meera, Dev true [ 1, 2 ]

Key points

  • Default sort compares strings in UTF-16 order, so numbers sort wrongly.
  • Use a comparator returning negative, zero, or positive; do not return a boolean.
  • sort mutates the array; use toSorted or copy first.
  • Sort is stable in modern engines.
  • Use localeCompare or Intl.Collator for human-readable text.

Common mistakes

  • Sorting numbers without a comparator.
  • Returning a boolean from the comparator.
  • Sorting an array that is part of shared state and mutating it by accident.
  • Using a - b with values that can be undefined, NaN, or strings; the result may be NaN, which is inconsistent.

Follow-ups

  • How would you sort objects by two keys, for example grade and then name?
  • What does a stable sort mean, and why did it matter in the specification change?
  • Why does the "random comparator" shuffle give a biased result?

Tips

  • Explain the string conversion first; it answers the question in one step.
  • Mention the mutation and stability points without being asked.
  • Recommend localeCompare for names. It shows you think about international users.
36.javascript-0036Mediummid

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

Object.groupBy(items, fn) and Map.groupBy(items, fn) build groups in one call in current runtimes. Before them, the standard approach was reduce with an accumulator object or Map. Choose Map when keys are not strings, and remember that the grouped arrays hold references to the original objects.

Full answer

Grouping means turning a flat list into buckets keyed by some value, for example students by grade or orders by city.

The modern tool is Object.groupBy(items, callback), available in Node.js 21 and recent browsers. The callback receives each item and returns the key. The result is an object with a null prototype whose values are arrays. Map.groupBy does the same but returns a Map, which supports keys of any type and keeps insertion order.

The older, portable way is reduce. The accumulator starts as an empty object or Map. For every item, the callback finds the key, creates the array if needed, and pushes the item. This pattern works everywhere and shows the idea behind the new methods.

Points worth saying aloud: the groups contain references to the same item objects, not copies. Keys of a plain object become strings, so grouping by a number gives string keys. A null-prototype result avoids clashes with names like constructor. Counting is a small variation: store a number instead of an array.

The work is one pass over the data, so the time is O(n) and the extra space is O(n).

javascript
const students = [
  { name: 'Asha', grade: 'B', marks: 72 },
  { name: 'Ravi', grade: 'A', marks: 91 },
  { name: 'Meera', grade: 'B', marks: 68 },
  { name: 'Dev', grade: 'A', marks: 88 },
  { name: 'Isha', grade: 'C', marks: 45 },
];

const byGrade = Object.groupBy(students, (student) => student.grade);
console.log(Object.keys(byGrade), byGrade.A.map((s) => s.name));

const byBand = Map.groupBy(students, (s) => (s.marks >= 80 ? 80 : 40));
console.log([...byBand.keys()], byBand.get(80).length);

function groupWithReduce(list, getKey) {
  return list.reduce((groups, item) => {
    const key = getKey(item);
    (groups[key] ??= []).push(item);
    return groups;
  }, {});
}
const manual = groupWithReduce(students, (s) => s.grade);
console.log(Object.keys(manual).map((key) => `${key}:${manual[key].length}`));

const counts = students.reduce((acc, s) => acc.set(s.grade, (acc.get(s.grade) ?? 0) + 1), new Map());
console.log(counts);

console.log(byGrade.A[0] === students[1], Object.getPrototypeOf(byGrade));

Run with Node.js v24.22.1 as js-36.js; two runs gave identical output. Output: [ 'B', 'A', 'C' ] [ 'Ravi', 'Dev' ] [ 40, 80 ] 2 [ 'B:2', 'A:2', 'C:1' ] Map(3) { 'B' => 2, 'A' => 2, 'C' => 1 } true null

Key points

  • Object.groupBy and Map.groupBy group in one call.
  • reduce with an accumulator is the portable alternative.
  • Object keys become strings; Map keeps the original key type.
  • Groups hold references to the original objects.
  • One pass: O(n) time and O(n) extra space.

Common mistakes

  • Forgetting to create the array for a new key before pushing.
  • Using a plain object when the keys are objects or need to stay numbers.
  • Mutating items inside a group and not realizing the original list changes too.
  • Using Object.groupBy in an environment that does not have it yet without a fallback.

Follow-ups

  • How would you group by two keys at once?
  • What does the result of Object.groupBy inherit from, and why does that matter?
  • How would you group and then compute the average of each group?

Tips

  • Show the reduce version first if the interviewer's runtime is unknown, then mention groupBy.
  • Say the time and space complexity as O(n) and O(n).
  • Use ??= for the "create if missing" step; it is short and shows modern syntax.
37.javascript-0037Hardsenior

What is the output order of code that mixes await, then, queueMicrotask, and setTimeout, and why?

Synchronous code runs first. Then all microtasks run in the order they were queued, including promise callbacks and the continuation after an await. Only then does the next timer callback run. An await on an already resolved value costs one microtask turn, and returning a promise from an async function or a then callback can add extra turns.

Full answer

To predict the order, simulate two queues: microtasks and macrotasks (timers). Run all synchronous lines, then empty the microtask queue completely, then take one timer.

In the snippet below, the lines inside an async function run synchronously up to the first await. At the await, the rest of the function is queued as a microtask for the moment the awaited value is ready. For a value that is already a native promise, or a plain value, that takes one microtask turn.

Promise callbacks join the queue when the promise is already resolved, or later when it resolves. Two chains of then calls advance in lockstep, one step per turn. A step inside one chain is interleaved with the step of the other, based on when each was queued.

An async function that returns a promise adds extra turns, because the returned promise has to be unwrapped. So return somePromise inside an async function resolves later than return value. The then callback returning a promise has the same extra cost.

Finally, the timer callbacks (setTimeout) run after the microtasks queued in the same turn, even with a delay of 0. Timers with a longer delay run later, and two timers with the same delay run in the order they were created.

Interviewers use this question to check that the candidate understands the queue model, not that anyone memorizes turn counts for exotic cases.

javascript
const log = (label) => console.log(label);

async function first() {
  log('first: start');
  await second();
  log('first: after await');
}

async function second() {
  log('second: running');
}

setTimeout(() => log('timeout 0'), 0);

first();

new Promise((resolve) => {
  log('promise executor');
  resolve();
})
  .then(() => log('then 1'))
  .then(() => log('then 2'));

queueMicrotask(() => log('queueMicrotask'));

(async () => {
  const plain = await 5;
  log('await plain value: ' + plain);
  const viaReturn = async () => Promise.resolve('returned promise');
  viaReturn().then(log);
  Promise.resolve('resolved directly').then(log);
})();

log('sync end');

Run with Node.js v24.22.1 as js-37.js; two runs gave identical output. Output: first: start second: running promise executor sync end first: after await then 1 queueMicrotask await plain value: 5 then 2 resolved directly returned promise timeout 0

Key points

  • Run synchronous code first; then drain all microtasks; then one timer.
  • Code before the first await runs synchronously.
  • await queues the continuation as a microtask.
  • Returning a promise from async or then adds extra microtask turns.
  • Timers with the same delay run in creation order.

Common mistakes

  • Treating await as if it blocks the program.
  • Forgetting that code before the first await runs synchronously.
  • Assuming a promise callback and a setTimeout callback with a zero delay are equal in priority.
  • Memorizing turn counts instead of understanding the queue model.

Follow-ups

  • How does the order change if the awaited value is a thenable that is not a native promise?
  • Where would process.nextTick callbacks appear in Node.js?
  • How does the order differ in a browser, where rendering can happen between macrotasks?

Tips

  • Keep two lists on the whiteboard: microtasks and timers. Update them after every line.
  • Say "first await continuation was queued before then 1" so the interviewer hears the reason, not only the answer.
  • If you are unsure about the extra turns for returned promises, say what you know and explain the unwrap step.
38.javascript-0038Hardsenior

What causes memory leaks in JavaScript applications, and how do you find and fix them?

JavaScript frees memory only for objects that can no longer be reached from a root, so a leak is an object that is still reachable but no longer needed. Common causes are forgotten event listeners, timers, unbounded caches, detached DOM nodes, and closures that hold large data. Find them by comparing heap snapshots over time and fix them by removing the reference.

Full answer

The garbage collector works by reachability. Starting from roots such as the global object and the current call stack, it marks every object it can reach and frees the rest. A leak therefore is not memory that is "lost". It is memory that something still points to, even though the program will never use it again.

The usual sources are these:

  • Event listeners that are added and never removed. The listener keeps its closure alive, and the target keeps the listener.
  • setInterval or a long setTimeout that is never cleared, together with the data its callback uses.
  • Caches and registries that only grow: a Map of results keyed by user input, an array of logged events, or a module-level list.
  • DOM nodes removed from the page but still referenced from a variable or a closure (detached nodes).
  • Closures that capture a large object when only a small part is needed.
  • Global variables created by accident.

To find a leak, repeat the suspect action many times in a profiler, take heap snapshots before and after, and compare which object counts grow (Chrome DevTools Memory tab, or node --inspect for Node.js). The retainers view shows the chain of references that keeps an object alive.

Fixes are to remove the reference: use removeEventListener or an AbortSignal to drop listeners together, clear timers on teardown, bound caches with a size limit or an expiry, use WeakMap or WeakRef where the key's lifetime should decide, and copy only needed fields into closures.

javascript
import { getEventListeners } from 'node:events';

const bus = new EventTarget();

function mountWidget(signal) {
  const bigData = new Array(1000).fill('x'); // stays alive while the listener exists
  bus.addEventListener('update', () => bigData.length, { signal });
}

// Leaky version: nothing removes the listeners.
for (let i = 0; i < 5; i++) mountWidget();
console.log('listeners after 5 mounts without cleanup:', getEventListeners(bus, 'update').length);

// Fixed version: one controller removes everything it registered.
const fresh = new EventTarget();
const controller = new AbortController();
for (let i = 0; i < 5; i++) {
  fresh.addEventListener('update', () => i, { signal: controller.signal });
}
console.log('listeners before abort:', getEventListeners(fresh, 'update').length);
controller.abort();
console.log('listeners after abort:', getEventListeners(fresh, 'update').length);

// Unbounded cache versus a bounded one.
const unbounded = new Map();
const bounded = new Map();
const LIMIT = 3;
for (let i = 0; i < 10; i++) {
  unbounded.set(`query-${i}`, i);
  bounded.set(`query-${i}`, i);
  if (bounded.size > LIMIT) bounded.delete(bounded.keys().next().value); // drop the oldest
}
console.log('unbounded size:', unbounded.size, 'bounded size:', bounded.size);

// Timers: an interval keeps its callback alive until it is cleared.
let ticks = 0;
const interval = setInterval(() => {
  ticks += 1;
  if (ticks === 2) {
    clearInterval(interval);
    console.log('interval cleared after', ticks, 'ticks');
  }
}, 5);

Run with Node.js v24.22.1 as js-38.mjs; two runs gave identical output. Output: listeners after 5 mounts without cleanup: 5 listeners before abort: 5 listeners after abort: 0 unbounded size: 10 bounded size: 3 interval cleared after 2 ticks

Key points

  • A leak is a still-reachable object that the program no longer needs.
  • Main causes: listeners, timers, unbounded caches, detached DOM nodes, large closures.
  • Heap snapshot comparison shows what grows; retainers show why.
  • AbortSignal can remove many listeners at once.
  • Bound caches and weak references limit growth.

Common mistakes

  • Saying JavaScript has no memory leaks because it has garbage collection.
  • Removing a DOM node but keeping a reference to it in a variable or array.
  • Passing a new function to removeEventListener, so it does not match the one that was added.
  • Guessing at the cause instead of comparing heap snapshots.

Follow-ups

  • How do WeakMap and WeakRef help, and what are their limits?
  • How would you detect a leak in a long-running Node.js server?
  • Why can a closure keep a whole scope alive even though it uses only one variable?

Tips

  • Define a leak as "reachable but unneeded"; it shows you understand how collection works.
  • Describe a profiling workflow: baseline, repeat the action, snapshot, compare, check retainers.
  • Give two fixes with code names: AbortSignal for listeners and a size limit for caches.
39.javascript-0039Hardsenior

What are WeakMap, WeakSet, and WeakRef, and when would you use them?

WeakMap and WeakSet hold their keys (objects or non-registered symbols) weakly, so an entry does not keep the key alive and disappears when the key is garbage collected. They cannot be iterated and have no size. WeakRef holds a weak pointer to one object, and FinalizationRegistry can run a callback after collection, but collection timing is never guaranteed.

Full answer

A normal Map keeps strong references to its keys, so a key stays in memory as long as the map exists. A WeakMap allows the key to be collected if nothing else refers to it, and then the entry vanishes automatically. Keys must be objects or non-registered symbols. A primitive key throws a TypeError.

Because entries can disappear at any time, the specification does not expose them. A WeakMap has only get, set, has, and delete, and a WeakSet has add, has, and delete. There is no iteration, no size, and no clear.

The best use is attaching extra data to an object you do not own without keeping that object alive. Examples are per-element data in a UI library, a cache of computed results keyed by an object, and truly private data keyed by the instance. Marking objects as "already visited" in a graph walk with a WeakSet is another use.

WeakRef wraps a single object. ref.deref() returns the object if it is still alive or undefined if it was collected. It suits optional caches of large objects. FinalizationRegistry lets code register a callback to run after an object is collected, for example to free an external resource.

These tools have a sharp edge: garbage collection is not predictable. The engine may delay collection, collect in a different order, or not collect before the program exits. Code must work correctly whether or not the callback ever runs, and must never depend on it for core logic. Always check the result of deref().

javascript
const metadata = new WeakMap();

function track(element) {
  const info = metadata.get(element) ?? { clicks: 0 };
  info.clicks += 1;
  metadata.set(element, info);
  return info.clicks;
}

const button = { id: 'save' };
console.log(track(button), track(button));
console.log(metadata.has(button), typeof metadata.size, typeof metadata[Symbol.iterator]);

try {
  metadata.set('primitive', 1);
} catch (error) {
  console.log('primitive key:', error.name);
}

const privateData = new WeakMap();
class Account {
  constructor(balance) {
    privateData.set(this, { balance });
  }
  get balance() {
    return privateData.get(this).balance;
  }
}
const account = new Account(500);
console.log(account.balance, Object.keys(account));

const visited = new WeakSet();
const nodeA = { name: 'A' };
visited.add(nodeA);
console.log(visited.has(nodeA), visited.has({ name: 'A' }));

const bigObject = { data: new Array(10).fill(0) };
const ref = new WeakRef(bigObject);
console.log(ref.deref() === bigObject); // still strongly referenced here, so it is alive

const registry = new FinalizationRegistry((label) => {
  console.log('collected:', label); // may run at any time later, or never
});
registry.register(bigObject, 'bigObject');
console.log('program does not depend on the callback');

Run with Node.js v24.22.1 as js-39.js; two runs gave identical output. Output: 1 2 true undefined undefined primitive key: TypeError 500 [] true false true program does not depend on the callback

Key points

  • Weak collections do not keep their keys alive; entries vanish after collection.
  • Keys must be objects or non-registered symbols.
  • No iteration, size, or clear on WeakMap and WeakSet.
  • WeakRef.deref() may return undefined; FinalizationRegistry callbacks may never run.
  • Use for metadata, caches, and private data tied to an object lifetime.

Common mistakes

  • Using a WeakMap and expecting to list its entries or count them.
  • Relying on a FinalizationRegistry callback to run on schedule.
  • Using a WeakRef for data that must exist, without handling undefined from deref().
  • Trying to use strings or numbers as WeakMap keys.

Follow-ups

  • Why is there no size property on a WeakMap?
  • How does a WeakMap differ from private class fields for private data?
  • Why does a WeakRef target stay alive for the rest of the current job after deref()?

Tips

  • Lead with "does not keep the key alive". The rest follows from that.
  • Give one use case, such as metadata attached to DOM elements.
  • Say clearly that garbage collection timing is unspecified, and that you never depend on it.
40.javascript-0040Hardsenior

What are Proxy and Reflect in JavaScript, and what are the limitations of Proxy?

A Proxy wraps an object and intercepts operations such as get, set, has, deleteProperty, and function calls through handler traps. Reflect provides the default behavior for each trap so a handler can forward the operation. Proxies enable validation, logging, default values, and reactive systems, but they change object identity, add overhead, and do not work transparently with internal slots such as private fields.

Full answer

new Proxy(target, handler) creates an object that stands in front of target. When code reads, writes, deletes, enumerates, or calls through the proxy, the engine looks for a matching function in handler, called a trap. If there is no trap, the operation goes straight to the target.

Common traps are get, set, has (for in), deleteProperty, ownKeys, apply (for function calls), and construct. The Reflect object has a method of the same name for each trap, such as Reflect.get and Reflect.set. Using it inside a trap performs the normal operation with correct receiver handling, and its return value tells the set trap whether to report success. In strict mode, a set trap that returns false throws a TypeError.

Uses include validation before assignment, default values for missing keys, logging, access control, and observable state, which is the foundation of the reactivity systems in modern UI frameworks. Proxy.revocable creates a proxy that can later be disabled.

Limitations matter in a senior discussion:

  • proxy !== target, so identity checks and WeakMap keys behave differently.
  • Built-in objects with internal slots, such as Map, Date, and class instances with private fields, may throw when a method is called with the proxy as this.
  • Every operation goes through a function call, which is slower than plain access in hot code.
  • Traps must obey invariants. For example, a non-configurable, non-writable property must report its real value.
  • Proxies cannot be fully polyfilled.
javascript
'use strict';

const validator = {
  set(target, property, value, receiver) {
    if (property === 'age' && (!Number.isInteger(value) || value < 0)) {
      throw new RangeError('age must be a non-negative integer');
    }
    return Reflect.set(target, property, value, receiver);
  },
  get(target, property, receiver) {
    return property in target ? Reflect.get(target, property, receiver) : `no ${String(property)}`;
  },
  has(target, property) {
    return !property.startsWith('_') && property in target;
  },
};

const person = new Proxy({ name: 'Leela', _secret: 'x' }, validator);
person.age = 30;
console.log(person.age, person.missing, 'age' in person, '_secret' in person);
try {
  person.age = -5;
} catch (error) {
  console.log(error.name, '-', error.message);
}

const calls = [];
const traced = new Proxy(function add(a, b) { return a + b; }, {
  apply(target, thisArg, args) {
    calls.push(args);
    return Reflect.apply(target, thisArg, args);
  },
});
console.log(traced(2, 3), calls);

class Counter {
  #count = 0;
  increment() {
    return ++this.#count;
  }
}
const counterProxy = new Proxy(new Counter(), {});
try {
  counterProxy.increment();
} catch (error) {
  console.log('private field through proxy:', error.name);
}
const fixedProxy = new Proxy(new Counter(), {
  get(target, property) {
    const value = Reflect.get(target, property, target);
    return typeof value === 'function' ? value.bind(target) : value;
  },
});
console.log(fixedProxy.increment());

const { proxy, revoke } = Proxy.revocable({ value: 1 }, {});
console.log(proxy.value);
revoke();
try {
  proxy.value;
} catch (error) {
  console.log('after revoke:', error.name);
}

Run with Node.js v24.22.1 as js-40.js; two runs gave identical output. Output: 30 no missing true false RangeError - age must be a non-negative integer 5 [ [ 2, 3 ] ] private field through proxy: TypeError 1 1 after revoke: TypeError

Key points

  • A Proxy intercepts operations through handler traps; missing traps forward to the target.
  • Reflect methods mirror the traps and give default behavior.
  • A set trap must return true for success; false throws in strict mode.
  • Proxies change identity and can break internal slots and private fields.
  • Useful for validation, defaults, logging, and reactivity; costs performance.

Common mistakes

  • Forgetting to return true from the set trap and getting a TypeError in strict mode.
  • Using target[property] instead of Reflect.get with the receiver, which breaks getters and inheritance.
  • Wrapping a Map or Date in a proxy and calling its methods without binding them.
  • Using a proxy in a hot loop without measuring the cost.

Follow-ups

  • How would you build a simple reactive state object with a Proxy?
  • What are proxy invariants, and what happens when a trap violates one?
  • How does a Proxy differ from Object.defineProperty for observing changes?

Tips

  • Name three traps and one real use for the set trap, such as validation.
  • Mention the private-field limit; it shows hands-on experience.
  • Explain that Reflect mirrors the traps and keeps behavior correct, instead of treating it as a separate topic.