← Interview prep

JavaScript interview questions

Language fundamentals, ES features, and async behavior.

200 questions · Page 9 of 10

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

Page 9 of 10

Questions 161–180 of 200 · 0 of 20 on this page marked learned

161.javascript-0161Easyfresher

How do you handle DOM events in JavaScript, and what is the difference between addEventListener and an onclick property?

addEventListener attaches any number of listeners to an element for an event type, with options such as once and passive, and removeEventListener removes them using the same function reference. An onclick property holds only one handler, and a new assignment replaces the old one. The handler receives an event object with target, currentTarget, preventDefault, and stopPropagation, and in a regular function this is the element.

Full answer

An event is a signal that something happened: a click, a key press, a form submit, or a page load. You react by registering a handler (a callback).

Three ways to register: an HTML attribute (<button onclick="run()">, which mixes markup and code and is best avoided), a property (button.onclick = fn), and button.addEventListener('click', fn). The property form allows only one handler per event type, and assigning again replaces it. addEventListener allows many listeners and gives options: { once: true } removes the listener after the first call, { passive: true } promises not to call preventDefault (useful for scroll and touch performance), and { capture: true } listens during the capture phase. To remove a listener, call removeEventListener with the same type and the same function reference, so anonymous functions cannot be removed.

The event object: event.type, event.target (the element that triggered the event), event.currentTarget (the element the listener is attached to), event.preventDefault() (stops the default action, such as a form submit or a link navigation), event.stopPropagation() (stops the event from moving to other elements), and for keyboard and mouse events, properties such as key, clientX, and shiftKey.

this and handlers: in a regular function handler, this is the element (the same as currentTarget). In an arrow function, this is taken from the surrounding scope, so use event.currentTarget there. Passing obj.method loses the object as this.

Other basics:

  • A handler may be an object with a handleEvent method.
  • Events fire in the order of registration for the same element and phase.
  • Custom events: element.dispatchEvent(new CustomEvent('name', { detail })).
  • submit events happen on the form, not the button, and preventDefault stops the page reload.
  • Remove listeners for elements that live long or that you re-create, to avoid leaks.
javascript
document.body.innerHTML = '<button id="btn">Click</button><form id="form"><input name="q" value="js"><button type="submit">Go</button></form>';
const button = document.getElementById('btn');
const log = [];

button.onclick = () => log.push('onclick A');
button.onclick = () => log.push('onclick B (replaced A)');
button.addEventListener('click', () => log.push('listener 1'));
button.addEventListener('click', () => log.push('listener 2'));
button.addEventListener('click', () => log.push('once only'), { once: true });
button.click();
button.click();
console.log(log);

// removing needs the same reference
const named = () => log.push('named handler');
button.addEventListener('click', named);
button.removeEventListener('click', named);
button.removeEventListener('click', () => {}); // a different function: nothing removed
log.length = 0;
button.click();
console.log(log);

// the event object and this
button.addEventListener('click', function (event) {
  console.log('regular function: this === currentTarget:', this === event.currentTarget, '| type:', event.type, '| target id:', event.target.id);
});
button.addEventListener('click', (event) => {
  console.log('arrow function: this is not the button:', this !== button, '| use event.currentTarget:', event.currentTarget.id);
});
button.click();

// preventDefault on a form submit
const form = document.getElementById('form');
form.addEventListener('submit', (event) => {
  event.preventDefault();
  console.log('submitted with value', new FormData(form).get('q'), '| defaultPrevented:', event.defaultPrevented);
});
form.requestSubmit();

// custom events
const box = document.createElement('div');
box.addEventListener('greet', (event) => console.log('custom event detail:', event.detail));
box.dispatchEvent(new CustomEvent('greet', { detail: { who: 'Asha' } }));

// handler objects
const handlerObject = { count: 0, handleEvent(event) { this.count++; console.log('handleEvent called, count', this.count, event.type); } };
button.addEventListener('click', handlerObject);
button.click();

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: [ 'onclick B (replaced A)', 'listener 1', 'listener 2', 'once only', 'onclick B (replaced A)', 'listener 1', 'listener 2' ] [ 'onclick B (replaced A)', 'listener 1', 'listener 2' ] regular function: this === currentTarget: true | type: click | target id: btn arrow function: this is not the button: true | use event.currentTarget: btn submitted with value js | defaultPrevented: true custom event detail: { who: 'Asha' } regular function: this === currentTarget: true | type: click | target id: btn arrow function: this is not the button: true | use event.currentTarget: btn handleEvent called, count 1 click

Key points

  • addEventListener allows many handlers and options (once, passive, capture); onclick keeps only one.
  • Remove a listener with the same function reference; anonymous functions cannot be removed.
  • Event object: target, currentTarget, preventDefault, stopPropagation, plus key and mouse details.
  • In a regular function this is the element; arrow functions need event.currentTarget.
  • Use submit on the form with preventDefault; clean up listeners you no longer need.

Common mistakes

  • Assigning onclick twice and losing the first handler.
  • Trying to remove an anonymous listener.
  • Using this inside an arrow function handler and expecting the element.
  • Listening for click on a submit button instead of submit on the form.

Follow-ups

  • What is the difference between target and currentTarget?
  • When would you use the passive option?
  • How does event delegation reduce the number of listeners?

Tips

  • State the main difference: one handler against many.
  • Mention the same-reference rule for removal.
  • Explain this in regular and arrow handlers.
162.javascript-0162Easyfresher

What is the difference between parseInt, parseFloat, and Number, and how do you round and format numbers for display?

Number(text) converts the whole string and gives NaN if any part is invalid, while parseInt and parseFloat read as many leading characters as they can and ignore the rest. Always pass a radix to parseInt. toFixed returns a string and rounds based on the binary value, so display money with Intl.NumberFormat or integer cents, and compare floating point results with a tolerance.

Full answer

Converting text to a number:

  • Number('42') is 42, Number('') is 0, Number(' 12 ') is 12, Number('12px') is NaN, and Number('0x1f') is 31. It is strict: the whole string must be a number.
  • parseInt('12px', 10) is 12. It reads digits from the start and stops at the first invalid character. parseInt('') is NaN. Always pass the radix as the second argument: parseInt('08', 10). parseInt(0.0000005) is 5 because the number is converted to the string '5e-7' first, so do not use it to truncate numbers. Use Math.trunc.
  • parseFloat('3.14abc') is 3.14, and it understands exponent notation. It has no radix.
  • Unary plus, +'42', behaves like Number.
  • Number.isNaN is the right way to check the result.

Rounding: Math.round, Math.floor, Math.ceil, and Math.trunc work on integers. For decimals, num.toFixed(2) returns a string, not a number, and its rounding follows the binary value: (1.005).toFixed(2) is '1.00', because 1.005 is stored slightly below 1.005. To round to decimals as a number, use Math.round(x * 100) / 100 with care, or Number(x.toFixed(2)). For money, keep integers (cents) or use a decimal library, and format only for display.

Formatting for people: num.toLocaleString('en-US') and Intl.NumberFormat add grouping, currency, percent, and compact notation, and follow local conventions (1.234,5 in German). Create one formatter and reuse it for lists.

Other checks: Number.isInteger, Number.isFinite (unlike the global isFinite, no conversion), Number.MAX_SAFE_INTEGER for exact integers, and toString(2) or parseInt(text, 2) for other bases. Floating point effects such as 0.1 + 0.2 !== 0.3 come from binary storage; compare with a small tolerance, Math.abs(a - b) < Number.EPSILON, for values near 1.

javascript
for (const text of ['42', '', ' 12 ', '12px', '3.14abc', '0x1f', '1e3', '-7', 'abc', '1,000']) {
  console.log(JSON.stringify(text).padEnd(10), 'Number:', String(Number(text)).padEnd(5), 'parseInt:', String(parseInt(text, 10)).padEnd(5), 'parseFloat:', parseFloat(text));
}
console.log(parseInt('08', 10), parseInt('ff', 16), parseInt('101', 2), (255).toString(16), (5).toString(2));
console.log('parseInt on a tiny number:', parseInt(0.0000005), '| Math.trunc:', Math.trunc(0.0000005));
console.log(['1', '2', '3'].map(Number), ['1', '2', '3'].map(parseInt));

console.log(Math.round(2.5), Math.round(-2.5), Math.round(2.4), Math.floor(-2.5), Math.ceil(-2.5), Math.trunc(-2.5));
console.log((1.005).toFixed(2), (1.255).toFixed(2), (2.5).toFixed(0), typeof (3).toFixed(2));
console.log(Math.round(1.005 * 100) / 100, Math.round((1.005 + Number.EPSILON) * 100) / 100);
console.log(0.1 + 0.2 === 0.3, Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);

const cents = 1999;
console.log('money as integer cents:', cents / 100, new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(cents / 100));
console.log((1234567.891).toLocaleString('en-US'), (1234567.891).toLocaleString('de-DE'), (1234567.891).toLocaleString('en-IN'));
console.log(new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 1 }).format(0.4567));
console.log(new Intl.NumberFormat('en', { notation: 'compact' }).format(1530000), new Intl.NumberFormat('en-US', { minimumFractionDigits: 2 }).format(5));

console.log(Number.isInteger(5.0), Number.isFinite('5'), isFinite('5'), Number.isNaN('abc'), isNaN('abc'));

Run with Node.js v24.22.1 as js-162.js; two runs gave identical output. Output: "42" Number: 42 parseInt: 42 parseFloat: 42 "" Number: 0 parseInt: NaN parseFloat: NaN " 12 " Number: 12 parseInt: 12 parseFloat: 12 "12px" Number: NaN parseInt: 12 parseFloat: 12 "3.14abc" Number: NaN parseInt: 3 parseFloat: 3.14 "0x1f" Number: 31 parseInt: 0 parseFloat: 0 "1e3" Number: 1000 parseInt: 1 parseFloat: 1000 "-7" Number: -7 parseInt: -7 parseFloat: -7 "abc" Number: NaN parseInt: NaN parseFloat: NaN "1,000" Number: NaN parseInt: 1 parseFloat: 1 8 255 5 ff 101 parseInt on a tiny number: 5 | Math.trunc: 0 [ 1, 2, 3 ] [ 1, NaN, NaN ] 3 -2 2 -3 -2 -2 1.00 1.25 3 string 1 1.01 false true money as integer cents: 19.99 $19.99 1,234,567.891 1.234.567,891 12,34,567.891 45.7% 1.5M 5.00 true false true false true

Key points

  • Number is strict and whole-string; parseInt and parseFloat read a valid prefix.
  • Always give parseInt a radix; do not use it to truncate numbers.
  • toFixed returns a string and can round unexpectedly; use cents or a decimal library for money.
  • Format for people with Intl.NumberFormat or toLocaleString.
  • Compare floats with a tolerance and check results with Number.isNaN.

Common mistakes

  • Calling parseInt without a radix, or passing it directly to map.
  • Using toFixed for calculations and forgetting that it returns a string.
  • Storing money as floating point numbers.
  • Using the global isNaN and isFinite, which convert their argument first.

Follow-ups

  • Why does (1.005).toFixed(2) give 1.00?
  • How would you round to the nearest 0.05?
  • How do you format a number with a currency symbol for different countries?

Tips

  • Contrast strict Number with the prefix-reading parse functions.
  • Give the money rule: integers or a decimal library, format for display only.
  • Mention Intl.NumberFormat for locales.
163.javascript-0163Easyfresher

How do the JSON.parse reviver and the JSON.stringify replacer and toJSON work, and how do you round-trip dates and Maps?

JSON.parse(text, reviver) calls the reviver for every key and value from the innermost values outward, so you can convert values such as date strings back into Date objects. JSON.stringify(value, replacer, space) lets you filter keys with an array or transform values with a function, and an object's toJSON method controls its own output. Dates become strings, and Map, Set, undefined, and functions need custom handling.

Full answer

JSON is text with a small set of types: objects, arrays, strings, numbers, booleans, and null. JavaScript values outside that set need rules.

JSON.stringify(value, replacer, space):

  • replacer as an array lists the property names that are kept (nested objects use the same list).
  • replacer as a function is called as replacer(key, value) for every pair, with this as the holder, starting with the key '' for the root. Return a new value to change the output, or undefined to drop the property.
  • space (a number or string) pretty-prints.
  • If a value has a toJSON() method, its result is used before the replacer runs. Date has one that returns an ISO string.
  • Defaults: undefined, functions, and symbols are dropped in objects and become null in arrays, NaN and Infinity become null, Map and Set become {}, and BigInt throws a TypeError.

JSON.parse(text, reviver): after parsing, the reviver is called as reviver(key, value) for each property, deepest first and the root last (with key ''). Return a value to replace it, or undefined to delete the property. Because JSON has no date type, dates arrive as strings, so a reviver can detect an ISO pattern and return a Date. Detecting by key name (createdAt) is safer than guessing from the string shape.

Round-tripping other types: write a replacer that tags values, such as { __type: 'Map', entries: [...] }, and a reviver that rebuilds them. For class instances, add a toJSON method and a static fromJSON.

Cautions: JSON.parse throws a SyntaxError on bad input, so wrap it with try. Circular structures throw a TypeError in stringify. Big integers lose precision when parsed as numbers. Never build objects from parsed JSON with unsafe merges (prototype pollution). Use structuredClone when you only need a deep copy within JavaScript.

javascript
const data = { id: 1, name: 'Asha', password: 'secret', createdAt: new Date('2026-03-05T10:30:00Z'), tags: ['a'], skip: undefined, run() {}, score: NaN };
console.log(JSON.stringify(data));
console.log(JSON.stringify(data, ['id', 'name']));
console.log(JSON.stringify(data, (key, value) => (key === 'password' ? undefined : value), 2));
console.log(JSON.stringify([undefined, () => {}, Symbol('s'), NaN, Infinity]));

class Money {
  constructor(cents, currency) { this.cents = cents; this.currency = currency; }
  toJSON() { return { amount: (this.cents / 100).toFixed(2), currency: this.currency }; }
  static fromJSON({ amount, currency }) { return new Money(Math.round(Number(amount) * 100), currency); }
}
console.log(JSON.stringify({ price: new Money(1999, 'USD') }));

const text = JSON.stringify({ when: new Date('2026-03-05T10:30:00Z'), n: 1 });
const plain = JSON.parse(text);
console.log('without a reviver:', typeof plain.when);
const revived = JSON.parse(text, (key, value) => (key === 'when' ? new Date(value) : value));
console.log('with a reviver:', revived.when instanceof Date, revived.when.getUTCFullYear());

const order = [];
JSON.parse('{"a": {"b": 1}, "c": 2}', function (key, value) { order.push(key === '' ? '(root)' : key); return value; });
console.log('reviver order, deepest first:', order);
console.log(JSON.parse('{"keep": 1, "drop": 2}', (key, value) => (key === 'drop' ? undefined : value)));

// Map and Set round trip with tags
const replacer = (key, value) => {
  if (value instanceof Map) return { __type: 'Map', entries: [...value] };
  if (value instanceof Set) return { __type: 'Set', values: [...value] };
  return value;
};
const reviver = (key, value) => {
  if (value && value.__type === 'Map') return new Map(value.entries);
  if (value && value.__type === 'Set') return new Set(value.values);
  return value;
};
const original = { users: new Map([[1, 'Asha']]), ids: new Set([1, 2]) };
console.log(JSON.stringify(original), JSON.stringify(original, replacer));
const restored = JSON.parse(JSON.stringify(original, replacer), reviver);
console.log(restored.users.get(1), restored.ids.has(2), restored.users instanceof Map);

for (const attempt of [() => JSON.stringify({ big: 10n }), () => JSON.parse('{bad json}'), () => { const loop = {}; loop.self = loop; JSON.stringify(loop); }]) {
  try { attempt(); } catch (error) { console.log(error.name); }
}
console.log(JSON.parse('12345678901234567890'));

Run with Node.js v24.22.1 as js-163.js; two runs gave identical output. Output: {"id":1,"name":"Asha","password":"secret","createdAt":"2026-03-05T10:30:00.000Z","tags":["a"],"score":null} {"id":1,"name":"Asha"} { "id": 1, "name": "Asha", "createdAt": "2026-03-05T10:30:00.000Z", "tags": [ "a" ], "score": null } [null,null,null,null,null] {"price":{"amount":"19.99","currency":"USD"}} without a reviver: string with a reviver: true 2026 reviver order, deepest first: [ 'b', 'a', 'c', '(root)' ] { keep: 1 } {"users":{},"ids":{}} {"users":{"__type":"Map","entries":[[1,"Asha"]]},"ids":{"__type":"Set","values":[1,2]}} Asha true true TypeError SyntaxError TypeError 12345678901234567000

Key points

  • Replacer arrays select keys; replacer functions transform or drop values; toJSON runs first.
  • Dates become strings; undefined, functions, and symbols are dropped; NaN becomes null; BigInt throws.
  • The reviver runs deepest first and can convert strings back to Dates; match by key name for safety.
  • Tag Map and Set values in the replacer and rebuild them in the reviver.
  • Wrap parse in try and watch circular data and large integers.

Common mistakes

  • Expecting dates to come back as Date objects without a reviver.
  • Serializing Map or Set directly and getting an empty object.
  • Calling JSON.parse on untrusted text without try and catch.
  • Putting secrets into objects that are later stringified, instead of filtering them.

Follow-ups

  • Why does the reviver run on the deepest values first?
  • How would you handle BigInt values in JSON?
  • What is the difference between JSON.stringify and structuredClone for copying?

Tips

  • Describe replacer and reviver as the two hooks, one for each direction.
  • Give the date example, since it is the most common need.
  • Mention what JSON drops silently.
164.javascript-0164Easyfresher

How do you write common string helpers such as capitalize, title case, truncate, word count, and reverse words?

Most helpers combine split, map, join, slice, and regular expressions. Capitalize with charAt(0).toUpperCase() plus slice(1), split words on whitespace with a regular expression, truncate by length and add an ellipsis that fits in the limit, and count words with match. Handle empty strings and extra whitespace, remember strings are immutable, and mention code points for emoji.

Full answer

These small tasks test knowledge of the string methods and attention to edge cases. Strings are immutable, so every helper returns a new string.

capitalize(text): take the first character, uppercase it, and join it with the rest: text.charAt(0).toUpperCase() + text.slice(1). charAt(0) returns an empty string for an empty input, while text[0] gives undefined, so charAt is safer. For titles, split into words, capitalize each, and join: text.toLowerCase().split(' ').map(capitalize).join(' ').

truncate(text, max): if text.length <= max, return it. Otherwise return text.slice(0, max - 1) + '…' so the result fits in max characters. A better version cuts at the last space before the limit so words are not split. Note that length counts UTF-16 units, so a cut can split an emoji; spread with [...text] for code points.

countWords(text): text.trim().split(/\s+/).filter(Boolean).length works. For an empty string, ''.split(/\s+/) gives [''], so the filter is needed. A regular expression with match(/\S+/g)?.length ?? 0 is another way.

reverseWords(text): text.trim().split(/\s+/).reverse().join(' ').

Other common ones: camelCase and kebab-case conversions with replace and a callback, slugify (lowercase, remove accents with normalize('NFD') and a range replace, replace non-alphanumerics with hyphens), isBlank (!text.trim()), countOccurrences (split(sub).length - 1 or matchAll), and padStart for ids.

Habits that interviewers like: check for non-string input if the function is public, do not mutate arguments, name edge cases (empty string, only spaces, repeated spaces, Unicode), and give the complexity (these are linear in the text length).

javascript
const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
const titleCase = (text) => text.toLowerCase().split(/\s+/).filter(Boolean).map(capitalize).join(' ');

function truncate(text, max, ellipsis = '\u2026') {
  if (text.length <= max) return text;
  const cut = text.slice(0, max - ellipsis.length);
  const lastSpace = cut.lastIndexOf(' ');
  return (lastSpace > 0 ? cut.slice(0, lastSpace) : cut) + ellipsis;
}

const countWords = (text) => text.trim().split(/\s+/).filter(Boolean).length;
const reverseWords = (text) => text.trim().split(/\s+/).reverse().join(' ');
const camelCase = (text) => text.toLowerCase().replace(/[^a-z0-9]+(.)/g, (_, ch) => ch.toUpperCase());
const kebabCase = (text) => text.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/[\s_]+/g, '-').toLowerCase();
const slugify = (text) => text.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
const countOccurrences = (text, part) => (part ? text.split(part).length - 1 : 0);
const isBlank = (text) => text.trim() === '';

console.log(capitalize('hello'), JSON.stringify(capitalize('')), titleCase('the QUICK  brown fox'));
console.log(truncate('JavaScript interview questions', 20), '|', truncate('short', 20), '|', truncate('Supercalifragilistic', 10));
console.log(countWords('  one  two   three '), countWords(''), countWords('   '), reverseWords('  the sky  is blue '));
console.log(camelCase('hello world-foo_bar'), kebabCase('helloWorld fooBar'), slugify('  Caf\u00e9 Cr\u00e8me: the Best!  '));
console.log(countOccurrences('banana', 'an'), countOccurrences('aaa', 'aa'), countOccurrences('abc', ''), isBlank('  \n'), isBlank(' a '));
console.log(String(7).padStart(3, '0'), 'ab'.padEnd(5, '.') + '|', 'x'.repeat(3));
console.log('emoji cut:', JSON.stringify('a\u{1F600}b'.slice(0, 2)), [...'a\u{1F600}b'].slice(0, 2).join('') === 'a\u{1F600}');

Run with Node.js v24.22.1 as js-164.js; two runs gave identical output. Output: Hello "" The Quick Brown Fox JavaScript… | short | Supercali… 3 0 0 blue is sky the helloWorldFooBar hello-world-foo-bar cafe-creme-the-best 2 1 0 true false 007 ab...| xxx emoji cut: "a\ud83d" true

Key points

  • Strings are immutable; every helper returns a new string.
  • Capitalize with charAt(0).toUpperCase() plus slice(1); title case maps it over words.
  • Truncate so the result including the ellipsis fits the limit; prefer cutting at a word boundary.
  • Count words by splitting on /\s+/ and filtering empty strings, or with match.
  • Handle empty input, extra spaces, and Unicode.

Common mistakes

  • Using text[0].toUpperCase() on an empty string, which throws a TypeError.
  • Counting words with split(' ') and getting wrong counts for repeated spaces.
  • Truncating to the limit and then adding the ellipsis, so the result is too long.
  • Expecting string methods to change the original string.

Follow-ups

  • How would you capitalize the first letter of each sentence?
  • How would you truncate HTML safely?
  • How would you count characters as a person sees them, including emoji?

Tips

  • Ask about empty input and extra spaces before coding.
  • Return new strings and say why.
  • Mention Unicode when you cut or reverse text.
165.javascript-0165Easyfresher

How do you shuffle an array correctly, and why is sort(() => Math.random() - 0.5) a bad idea?

Use the Fisher-Yates shuffle: walk from the end of the array, pick a random index from 0 to the current position, and swap, which gives every permutation the same probability in O(n) time. Sorting with a random comparator is biased and engine-dependent, because the comparator is inconsistent. For security uses such as tokens, use crypto.getRandomValues, not Math.random.

Full answer

A shuffle should make every possible order equally likely. For an array of n items there are n factorial orders.

Fisher-Yates: for i from n - 1 down to 1, choose a random integer j with 0 <= j <= i, and swap a[i] and a[j]. Each position is filled once, and each item has an equal chance to land in each place. It runs in O(n) time and O(1) extra space when shuffling in place. Copy the array first if the original must stay unchanged.

Random integers: Math.floor(Math.random() * (max + 1)) gives 0..max. The classic bug is using Math.round, which makes the first and last values half as likely, or using i + 1 incorrectly and producing a modulo or off-by-one bias. Another common mistake is choosing j from the whole array on every step (0..n-1), which looks right but is biased: it produces n to the power n equally likely paths that cannot map evenly onto n! orders.

Why array.sort(() => Math.random() - 0.5) is wrong: a comparator must be consistent (the same two items must always compare the same way). A random comparator breaks this rule, so the sort algorithm gets contradictory answers, and the result depends on the algorithm of the engine. Results are visibly biased: some items stay near their start position much more often than chance. It is also O(n log n) instead of O(n).

Sampling: to pick k random items without repeats, run only the first k steps of a Fisher-Yates shuffle, or shuffle a copy and take k. To pick one item: items[Math.floor(Math.random() * items.length)].

Security: Math.random is not cryptographically secure and cannot be seeded. For tokens, passwords, or a fair draw with money at stake, use crypto.getRandomValues (browsers and Node.js). For repeatable tests, use a seeded generator such as mulberry32 so the output is the same on every run.

javascript
// a small seeded generator, so the demonstration gives the same output on every run
function mulberry32(seed) {
  return function () {
    seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function shuffle(items, random = Math.random) {
  const copy = items.slice();
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

function badShuffle(items, random) {
  const copy = items.slice();
  for (let i = 0; i < copy.length; i++) {
    const j = Math.floor(random() * copy.length); // wrong: chooses from the whole array
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

const sample = (items, k, random) => shuffle(items, random).slice(0, k);

// count how often each permutation of [1, 2, 3] appears in 60000 shuffles
function distribution(method, random) {
  const counts = {};
  for (let run = 0; run < 60000; run++) {
    const key = method([1, 2, 3], random).join('');
    counts[key] = (counts[key] ?? 0) + 1;
  }
  return Object.fromEntries(Object.entries(counts).sort());
}

const random = mulberry32(2026);
console.log('Fisher-Yates (about 10000 each):', distribution(shuffle, random));
console.log('wrong version (uneven):          ', distribution(badShuffle, random));
const biasedSort = (items, rnd) => items.slice().sort(() => rnd() - 0.5);
console.log('random comparator sort:          ', distribution(biasedSort, random));

const original = [1, 2, 3, 4, 5];
const mixed = shuffle(original, mulberry32(7));
console.log(original, mixed, 'same items:', [...mixed].sort().join() === original.join());
console.log('sample of 2:', sample(['a', 'b', 'c', 'd', 'e'], 2, mulberry32(3)));

const token = crypto.getRandomValues(new Uint8Array(8));
console.log('secure random bytes:', token.length, 'values in range:', [...token].every((b) => b >= 0 && b <= 255));
const randomInt = (min, max, rnd = Math.random) => Math.floor(rnd() * (max - min + 1)) + min;
console.log('dice rolls:', Array.from({ length: 8 }, () => randomInt(1, 6, mulberry32(11))).length, 'range ok:', randomInt(1, 6) >= 1 && randomInt(1, 6) <= 6);

Run with Node.js v24.22.1 as js-165.js; two runs gave identical output. Output: Fisher-Yates (about 10000 each): { '123': 9976, '132': 9934, '213': 10018, '231': 9914, '312': 10033, '321': 10125 } wrong version (uneven): { '123': 8951, '132': 11177, '213': 11037, '231': 11005, '312': 8866, '321': 8964 } random comparator sort: { '123': 22289, '132': 3766, '213': 7529, '231': 3794, '312': 3758, '321': 18864 } [ 1, 2, 3, 4, 5 ] [ 4, 2, 3, 5, 1 ] same items: true sample of 2: [ 'c', 'e' ] secure random bytes: 8 values in range: true dice rolls: 8 range ok: true

Key points

  • Fisher-Yates: loop from the end, swap with a random index from 0 to i; unbiased and O(n).
  • Use Math.floor(Math.random() * (i + 1)); avoid Math.round and choosing from the whole array each time.
  • A random sort comparator is inconsistent, so it is biased and engine-dependent.
  • Sampling k items means running k steps of the shuffle.
  • Use crypto.getRandomValues for security and a seeded generator for tests.

Common mistakes

  • Shuffling with sort(() => Math.random() - 0.5).
  • Choosing the swap index from the whole array in every step.
  • Using Math.round to build a random integer.
  • Using Math.random for tokens, passwords, or security decisions.

Follow-ups

  • Why does choosing from the whole array give n to the n paths, and why is that biased?
  • How would you pick a random item with weights?
  • How does crypto.getRandomValues differ from Math.random?

Tips

  • Name Fisher-Yates and describe it in one sentence.
  • Explain why the random comparator is invalid.
  • Say that you would test the fairness by counting permutations of a small array.
166.javascript-0166Easyfresher

How do you solve common array warm-ups: rotate an array, find the second largest value, find a missing number, and merge two sorted arrays?

Rotate with slice and modulo or three reversals, find the second largest in one pass by tracking the two best values, find the missing number in 0..n by comparing the expected sum or using XOR, and merge sorted arrays with two indexes in O(n + m). State the edge cases: empty input, duplicates, negative values, and k larger than the length.

Full answer

These problems appear in screens because each has a clean linear solution and several traps.

Rotate right by k: use k % n first, so large k works and an empty array does not divide by zero. A simple answer is arr.slice(-k).concat(arr.slice(0, -k)) with care for k === 0 (since slice(-0) returns the whole array). An in-place version reverses the whole array, then the first k items, then the rest, using O(1) extra space.

Second largest: sorting works in O(n log n) but one pass is better. Keep first and second as -Infinity. For each value, if it is greater than first, move first to second and set first; else if it is greater than second and different from first, set second. Decide how to treat duplicates (distinct second largest or not) and what to return when it does not exist.

Missing number in 0..n (array has n numbers, one missing): the expected sum is n * (n + 1) / 2, so the answer is the expected sum minus the actual sum. XOR gives the same result without any risk of large sums: XOR all indexes and values; pairs cancel and the missing one remains. Both are O(n) time and O(1) space. For sums, mention that values stay exact in doubles up to 2 to the 53.

Merge two sorted arrays: keep indexes i and j, push the smaller head, then append what is left. It is O(n + m). Use <= to keep it stable. Do not use concat plus sort, which is O(n log n) and, without a numeric comparator, sorts as strings.

Also common: finding duplicates with a Set, flattening with recursion, and chunking.

Interview habit: ask about input size and duplicates, write the simple solution first, then improve and name the complexity.

javascript
function rotateRight(array, k) {
  if (array.length === 0) return [];
  const shift = ((k % array.length) + array.length) % array.length;
  return shift === 0 ? array.slice() : array.slice(-shift).concat(array.slice(0, -shift));
}

function rotateInPlace(array, k) {
  const n = array.length;
  if (n === 0) return array;
  k = ((k % n) + n) % n;
  const reverse = (from, to) => {
    for (; from < to; from++, to--) [array[from], array[to]] = [array[to], array[from]];
  };
  reverse(0, n - 1);
  reverse(0, k - 1);
  reverse(k, n - 1);
  return array;
}

function secondLargest(numbers) {
  let first = -Infinity;
  let second = -Infinity;
  for (const n of numbers) {
    if (n > first) {
      second = first;
      first = n;
    } else if (n > second && n < first) {
      second = n;
    }
  }
  return second === -Infinity ? undefined : second;
}

const missingBySum = (numbers) => (numbers.length * (numbers.length + 1)) / 2 - numbers.reduce((a, b) => a + b, 0);
function missingByXor(numbers) {
  let result = numbers.length;
  numbers.forEach((value, index) => { result ^= index ^ value; });
  return result;
}

function mergeSorted(a, b) {
  const out = [];
  let i = 0;
  let j = 0;
  while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
  while (i < a.length) out.push(a[i++]);
  while (j < b.length) out.push(b[j++]);
  return out;
}

console.log(rotateRight([1, 2, 3, 4, 5], 2), rotateRight([1, 2, 3], 0), rotateRight([1, 2, 3], 7), rotateRight([1, 2, 3], -1), rotateRight([], 3));
console.log(rotateInPlace([1, 2, 3, 4, 5, 6, 7], 3), rotateInPlace([1], 5));
console.log(secondLargest([3, 9, 4, 9, 1]), secondLargest([5, 5]), secondLargest([7]), secondLargest([-1, -5, -3]), secondLargest([]));
console.log(missingBySum([3, 0, 1]), missingByXor([3, 0, 1]), missingBySum([0, 1]), missingByXor([9, 6, 4, 2, 3, 5, 7, 0, 1]));
console.log(mergeSorted([1, 4, 9], [2, 3, 10, 11]), mergeSorted([], [1]), mergeSorted([5, 5], [5]));
console.log([10, 9, 1].concat([2]).sort(), [10, 9, 1, 2].sort((a, b) => a - b));

Run with Node.js v24.22.1 as js-166.js; two runs gave identical output. Output: [ 4, 5, 1, 2, 3 ] [ 1, 2, 3 ] [ 3, 1, 2 ] [ 2, 3, 1 ] [] [ 5, 6, 7, 1, 2, 3, 4 ] [ 1 ] 4 undefined undefined -3 undefined 2 2 2 8 [ 1, 2, 3, 4, 9, 10, 11 ] [ 1 ] [ 5, 5, 5 ] [ 1, 10, 2, 9 ] [ 1, 2, 9, 10 ]

Key points

  • Rotate: normalize k with modulo; slice and concat, or three in-place reversals.
  • Second largest: one pass with two variables; decide how to treat duplicates and short arrays.
  • Missing number: expected sum minus actual sum, or XOR; both O(n) time, O(1) space.
  • Merge sorted arrays with two pointers in O(n + m); do not concat and sort.
  • Clarify edge cases and state complexity.

Common mistakes

  • Forgetting k % n, or dividing by zero for an empty array.
  • Sorting to find the second largest when a single pass is enough.
  • Returning the largest value as the second largest for arrays with duplicates, without stating the rule.
  • Merging with concat and the default sort.

Follow-ups

  • How would you rotate a linked list or a matrix?
  • How would the second largest solution change for the kth largest?
  • How would you find two missing numbers?

Tips

  • Ask about duplicates, negative numbers, and empty input.
  • Offer the simple answer first, then the improved one.
  • Say the complexity of each version.
167.javascript-0167Mediummid

Which of these temporal dead zone puzzles throw, which print a value, and what rule explains each?

let, const, and class declarations are hoisted but not initialized, so reading them before their line runs throws a ReferenceError for the whole block from its start. This also applies to typeof, to default parameters that refer to later parameters, and to a variable used in its own initializer. A function called later is fine, because the check happens when the variable is read, not when it is written in code.

Full answer

The temporal dead zone (TDZ) is the span from the start of a scope to the line where a let, const, or class declaration is evaluated. In that span the binding exists but is uninitialized, and any read or write, including typeof, throws a ReferenceError.

The puzzles and their rules:

  1. Reading before the line: console.log(a); let a = 1; throws. With var it prints undefined, because var is initialized to undefined at the start of the function.
  2. typeof is not a safe check inside the TDZ: typeof b; let b; throws, although typeof of a name that is never declared returns 'undefined'.
  3. Self reference: let x = x; throws, because the right side runs while x is still in the dead zone. var x = x gives undefined.
  4. Default parameters have their own scope and are evaluated left to right: function f(a = b, b = 1) throws if a uses the default, because b is not initialized yet. function f(a = 1, b = a) works.
  5. Function bodies called later: function show() { return value; } let value = 5; show(); works if show is called after the declaration ran. If show() is called before, it throws, because the check is at read time.
  6. Shadowing: an inner let with the same name as an outer variable creates a dead zone for the inner block, even for earlier lines: let v = 1; { console.log(v); let v = 2; } throws, and it does not print the outer 1.
  7. Classes: new Foo(); class Foo {} throws. A class is hoisted like let, unlike a function declaration, which is fully hoisted.
  8. switch cases share one block scope: switch (1) { case 0: let t = 1; break; case 1: console.log(t); } throws, because the case that declares t was never run. Use braces around the case body.
  9. const and let in loops are per iteration, so for (let i = 0; ...) has no TDZ problem, but for (let i = i; ...) does.

Why it exists: it catches use-before-define bugs and makes const meaningful. A cheap rule: declare variables at the top of their scope before using them.

javascript
const attempt = (label, fn) => {
  try {
    console.log(label.padEnd(34), '->', fn());
  } catch (error) {
    console.log(label.padEnd(34), '->', error.name);
  }
};

attempt('1. let read before declaration', () => { const read = () => value; const result = read(); let value = 1; return result; });
attempt('1b. var read before declaration', () => { const result = early; var early = 1; return result; });
attempt('2. typeof in the dead zone', () => { const t = typeof inside; let inside = 1; return t; });
attempt('2b. typeof of an undeclared name', () => typeof neverDeclared);
attempt('3. let x = x', () => { let x = x; return x; });
attempt('3b. var x = x', () => { var x = x; return x; });
attempt('4. default uses a later parameter', () => ((a = b, b = 1) => [a, b])());
attempt('4b. default uses an earlier one', () => ((a = 1, b = a + 1) => [a, b])());
attempt('4c. only the second argument given', () => ((a = b, b = 1) => [a, b])(undefined, 5));

attempt('5. function called after declaration', () => {
  function show() { return later; }
  let later = 5;
  return show();
});
attempt('5b. function called before declaration', () => {
  function show() { return later; }
  const result = show();
  let later = 5;
  return result;
});

attempt('6. inner let shadows the outer one', () => {
  let v = 1;
  {
    const seen = () => v;
    const out = seen();
    let v = 2;
    return [out, v];
  }
});
attempt('6b. without the inner declaration', () => {
  let v = 1;
  { return v; }
});

attempt('7. class used before definition', () => { const instance = new Foo(); class Foo {} return instance; });
attempt('7b. function declaration is hoisted', () => { const result = hoisted(); function hoisted() { return 'ok'; } return result; });

attempt('8. switch cases share one scope', () => {
  switch (1) {
    case 0: let t = 'zero'; break;
    case 1: return t;
  }
});
attempt('8b. braces fix it', () => {
  switch (0) {
    case 0: { let t = 'zero'; return t; }
  }
});

attempt('9. for (let i = i; ...)', () => { for (let i = i; i < 1; i++) return i; });
attempt('9b. normal let loop', () => { const out = []; for (let i = 0; i < 3; i++) out.push(() => i); return out.map((f) => f()); });
attempt('10. const assignment after init', () => { const c = 1; c = 2; return c; });

Run with Node.js v24.22.1 as js-167.js; two runs gave identical output. Output: 1. let read before declaration -> ReferenceError 1b. var read before declaration -> undefined 2. typeof in the dead zone -> ReferenceError 2b. typeof of an undeclared name -> undefined 3. let x = x -> ReferenceError 3b. var x = x -> undefined 4. default uses a later parameter -> ReferenceError 4b. default uses an earlier one -> [ 1, 2 ] 4c. only the second argument given -> ReferenceError 5. function called after declaration -> 5 5b. function called before declaration -> ReferenceError 6. inner let shadows the outer one -> ReferenceError 6b. without the inner declaration -> 1 7. class used before definition -> ReferenceError 7b. function declaration is hoisted -> ok 8. switch cases share one scope -> ReferenceError 8b. braces fix it -> zero 9. for (let i = i; ...) -> ReferenceError 9b. normal let loop -> [ 0, 1, 2 ] 10. const assignment after init -> TypeError

Key points

  • let, const, and class are hoisted but uninitialized until their declaration runs; reading earlier throws ReferenceError.
  • typeof does not protect against the TDZ; var gives undefined instead.
  • Default parameters are evaluated left to right and cannot use later parameters.
  • An inner let creates a dead zone for the whole inner block, hiding the outer variable.
  • Functions can use later declarations if they are called afterwards; switch cases need braces.

Common mistakes

  • Believing that let and const are not hoisted at all.
  • Using typeof to guard a variable that is declared later in the same scope.
  • Using a later parameter in an earlier default value.
  • Declaring variables inside switch cases without braces.

Follow-ups

  • What is the difference between the temporal dead zone and var hoisting?
  • Why does a class behave like let and not like a function declaration?
  • How does the TDZ show up with circular imports in ES modules?

Tips

  • Say that the binding exists from the start of the scope but is uninitialized.
  • Walk through the shadowing puzzle, since it surprises most people.
  • Give the practical rule: declare before use and use braces in switch cases.
168.javascript-0168Mediummid

What do these closures-in-loops puzzles print, and why do var and let behave differently?

Closures capture variables, not values. A var loop has one shared variable that has reached its final value when the callbacks run, so they all see the same number. A let loop creates a new binding for each iteration, so each callback sees its own copy. The fixes for var code are let, an IIFE or function parameter that copies the value, or forEach and map, whose callbacks get their own parameters.

Full answer

A closure keeps a reference to the variable in the scope where the function was created. It does not copy the value at that moment. That explains the classic puzzle: for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)) prints 3, 3, 3. There is one i for the whole function. The loop finishes first, i is 3, and then the callbacks run and read that one variable.

With let, the specification creates a fresh binding for each iteration and copies the value of the previous iteration into it before the increment runs. So the callbacks see 0, 1, 2. Details worth noting: the copy happens before the update expression (i++), so each closure gets a variable that is not changed by later increments, but a closure can still change its own copy.

Variants and rules:

  • forEach, map, and for...of with const: each call or iteration has a new binding, so they work.
  • for (var i...) { let j = i; fns.push(() => j); } works, since let j is created inside the block on each iteration.
  • An IIFE or a helper function with a parameter copies the value into a new scope: (function (n) {...})(i).
  • setTimeout(fn, 0, i) passes the current value as an argument at the time of the call, which also works.
  • Closures over an object share the object: pushing functions that read obj.count see updates made later.
  • for (let i...) with a closure that changes i inside the body changes the loop counter of that iteration, which then affects the next iteration through the copy step.
  • Closures created in while loops with let declared inside the body have new bindings per pass, but a let declared before the loop is shared.

The deep point: the output depends on when the callback runs and which binding it reads, not on the loop syntax alone. When you explain, name the binding and the moment of reading.

javascript
const run = (label, build) => {
  const fns = build();
  console.log(label.padEnd(36), fns.map((fn) => fn()));
};

run('1. var in a for loop', () => {
  const fns = [];
  for (var i = 0; i < 3; i++) fns.push(() => i);
  return fns;
});
run('2. let in a for loop', () => {
  const fns = [];
  for (let i = 0; i < 3; i++) fns.push(() => i);
  return fns;
});
run('3. var with an IIFE copy', () => {
  const fns = [];
  for (var i = 0; i < 3; i++) (function (n) { fns.push(() => n); })(i);
  return fns;
});
run('4. var with a let copy in the body', () => {
  const fns = [];
  for (var i = 0; i < 3; i++) { let copy = i; fns.push(() => copy); }
  return fns;
});
run('5. forEach callback parameter', () => {
  const fns = [];
  [10, 20, 30].forEach((value) => fns.push(() => value));
  return fns;
});
run('6. let declared before the loop', () => {
  const fns = [];
  let shared = 0;
  for (; shared < 3; shared++) fns.push(() => shared);
  return fns;
});
run('7. closure shares an object', () => {
  const fns = [];
  const counter = { count: 0 };
  for (let k = 0; k < 3; k++) { counter.count++; fns.push(() => counter.count); }
  return fns;
});
run('8. for...in with var', () => {
  const fns = [];
  for (var key in { a: 1, b: 2 }) fns.push(() => key);
  return fns;
});
run('9. for...in with const', () => {
  const fns = [];
  for (const key in { a: 1, b: 2 }) fns.push(() => key);
  return fns;
});
run('10. closure changes its own copy', () => {
  const fns = [];
  for (let i = 0; i < 3; i++) fns.push(() => ++i);
  return fns.concat(fns).slice(0, 4);
});
run('11. increment inside the body', () => {
  const fns = [];
  for (let i = 0; i < 6; i++) { fns.push(() => i); i++; }
  return fns;
});

const results = [];
for (var t = 0; t < 3; t++) setTimeout(() => results.push(['var timeout', t]), 0);
for (let u = 0; u < 3; u++) setTimeout(() => results.push(['let timeout', u]), 0);
for (var w = 0; w < 3; w++) setTimeout((n) => results.push(['argument', n]), 0, w);
setTimeout(() => console.log(results.map(([label, v]) => `${label}:${v}`).join(' ')), 5);

Run with Node.js v24.22.1 as js-168.js; two runs gave identical output. Output: 1. var in a for loop [ 3, 3, 3 ] 2. let in a for loop [ 0, 1, 2 ] 3. var with an IIFE copy [ 0, 1, 2 ] 4. var with a let copy in the body [ 0, 1, 2 ] 5. forEach callback parameter [ 10, 20, 30 ] 6. let declared before the loop [ 3, 3, 3 ] 7. closure shares an object [ 3, 3, 3 ] 8. for...in with var [ 'b', 'b' ] 9. for...in with const [ 'a', 'b' ] 10. closure changes its own copy [ 1, 2, 3, 2 ] 11. increment inside the body [ 1, 3, 5 ] var timeout:3 var timeout:3 var timeout:3 let timeout:0 let timeout:1 let timeout:2 argument:0 argument:1 argument:2

Key points

  • Closures capture variables, not values; a var loop has one shared variable.
  • let creates a new binding per iteration, copied from the previous one.
  • Fixes: let, a block-scoped copy, an IIFE or parameter, forEach or map, or passing an argument to setTimeout.
  • Objects captured by closures are shared and show later changes.
  • A let declared before a loop is shared; one declared inside the body is per pass.

Common mistakes

  • Explaining the var result as the value being copied late, instead of one shared variable.
  • Using var in loops that create callbacks.
  • Assuming let creates a new variable only when you declare it inside the body.
  • Capturing a mutable object and expecting a snapshot.

Follow-ups

  • How does the specification copy the let binding between iterations?
  • Why does for...of with const work even though const cannot change?
  • How would you fix the var version without changing the loop to let?

Tips

  • Say closures capture variables, then name which variable each callback reads.
  • Give two fixes: let, and passing an argument.
  • Mention that timing matters: the loop ends before the callbacks run.
169.javascript-0169Mediummid

What does this refer to in these callback and class puzzles, and how do you fix each one?

this is set by how a function is called, not where it is written, except for arrow functions, which take this from the surrounding scope. A method passed as a callback loses its object, a timer or array callback gets undefined or the global object, bind fixes this permanently and cannot be changed by call, and arrow class fields bind this per instance. Constructors called without new fail in classes.

Full answer

The rule of thumb: for a regular function, this is decided at the call site. obj.method() sets this to obj. method() alone gives undefined in strict mode (and always in classes and modules) and the global object in sloppy mode. fn.call(x), fn.apply(x), and fn.bind(x) set it explicitly. new Fn() creates a new object as this. An arrow function has no this of its own and uses the one of the scope where it was defined.

Puzzles:

  1. A method extracted into a variable, or passed as a callback, loses its object. In a class, the call throws a TypeError when it reads a property of undefined.
  2. setTimeout(obj.method, 0) calls the function without the object. In browsers this is the window, and in Node.js it is the Timeout object. Neither is your object.
  3. Array method callbacks (forEach, map) receive this as undefined unless a second thisArg argument is given.
  4. An arrow function inside a method keeps the method's this, so it works for timers inside methods. An arrow function as an object literal method does not, because it takes this from the outer scope, not from the object.
  5. bind creates a function with a fixed this. Binding again, or calling it with call, cannot change it. new on a bound function ignores the bound this.
  6. A class field with an arrow function (handle = () => ...) creates one function per instance with this fixed to that instance, which survives being passed around. A normal method lives on the prototype and does not.
  7. In a subclass constructor, this cannot be used before super() is called, and calling a class without new throws.

Fixes: bind in the constructor or at the call site, wrap in an arrow function, use an arrow class field, or avoid this by closing over a variable. Name which one you choose and the trade-off: arrow fields cost memory per instance and cannot be overridden through super.

javascript
'use strict';
const attempt = (label, fn) => {
  try {
    console.log(label.padEnd(36), '->', fn());
  } catch (error) {
    console.log(label.padEnd(36), '->', error.name);
  }
};

class Counter {
  count = 0;
  constructor(label) { this.label = label; }
  inc() { return `${this.label}:${++this.count}`; }
  incArrow = () => `${this.label}:${++this.count}`;
}
const counter = new Counter('c1');

attempt('1. method called normally', () => counter.inc());
attempt('1b. method extracted', () => { const { inc } = counter; return inc(); });
attempt('1c. arrow field extracted', () => { const { incArrow } = counter; return incArrow(); });
attempt('1d. bound method extracted', () => { const bound = counter.inc.bind(counter); return bound(); });
attempt('1e. wrapped in an arrow', () => [1].map(() => counter.inc()));

attempt('2. array callback, no thisArg', () => [1].map(counter.inc));
attempt('2b. array callback with thisArg', () => [1].map(counter.inc, counter));

const obj = {
  name: 'obj',
  regular() { return this?.name; },
  arrow: () => (typeof this === 'object' ? Object.keys(this).length + ' keys on module.exports' : typeof this),
  later() { return [1].map(() => this.name); },
  laterRegular() { return [1].map(function () { return this?.name; }); },
};
attempt('4. regular method', () => obj.regular());
attempt('4b. arrow as object method', () => obj.arrow());
attempt('4c. arrow inside a method', () => obj.later());
attempt('4d. regular function inside a method', () => obj.laterRegular());

function whoAmI() { return this?.id; }
const a = { id: 'a' };
const b = { id: 'b' };
const boundToA = whoAmI.bind(a);
attempt('5. bind then call with b', () => boundToA.call(b));
attempt('5b. bind twice', () => whoAmI.bind(a).bind(b)());
attempt('5c. call', () => whoAmI.call(b));
attempt('5d. new on a bound function', () => { function Person(name) { this.name = name; } const BoundPerson = Person.bind({ ignored: true }); return new BoundPerson('Asha').name; });

attempt('7. class called without new', () => Counter('x'));
attempt('7b. this before super', () => { class A {} class B extends A { constructor() { this.x = 1; super(); } } return new B(); });

attempt('8. arrow field is per instance', () => new Counter('x').incArrow === new Counter('y').incArrow);
attempt('8b. prototype method is shared', () => new Counter('x').inc === new Counter('y').inc);

setTimeout(function () { console.log('timer callback, regular function, this is the timer:', this?.constructor?.name); }, 1);
setTimeout(() => console.log('timer callback, arrow function, this is module.exports:', this === module.exports), 2);

Run with Node.js v24.22.1 as js-169.js; two runs gave identical output. Output: 1. method called normally -> c1:1 1b. method extracted -> TypeError 1c. arrow field extracted -> c1:2 1d. bound method extracted -> c1:3 1e. wrapped in an arrow -> [ 'c1:4' ] 2. array callback, no thisArg -> TypeError 2b. array callback with thisArg -> [ 'c1:5' ] 4. regular method -> obj 4b. arrow as object method -> 0 keys on module.exports 4c. arrow inside a method -> [ 'obj' ] 4d. regular function inside a method -> [ undefined ] 5. bind then call with b -> a 5b. bind twice -> a 5c. call -> b 5d. new on a bound function -> Asha 7. class called without new -> TypeError 7b. this before super -> ReferenceError 8. arrow field is per instance -> false 8b. prototype method is shared -> true timer callback, regular function, this is the timer: Timeout timer callback, arrow function, this is module.exports: true

Key points

  • Regular functions: this comes from the call; arrow functions use this from the enclosing scope.
  • Extracted or callback methods lose their object; timers and array callbacks give undefined, the global object, or the timer.
  • bind fixes this for good; call and apply cannot override it, and new ignores it.
  • Arrow class fields give per-instance binding; object literal arrow methods do not get the object.
  • In derived constructors, use this only after super(); classes cannot be called without new.

Common mistakes

  • Passing obj.method as a callback and expecting this to be obj.
  • Using an arrow function as an object literal method.
  • Trying to change this on a bound function with call or apply.
  • Using this before super() in a derived constructor.

Follow-ups

  • What are the trade-offs of arrow functions as class fields?
  • How does new work on a bound function?
  • How do you pass the right this to a DOM event listener?

Tips

  • Start from the rule: the call site decides, except in arrow functions.
  • Give the three fixes: bind, arrow wrapper, arrow field.
  • Mention the memory cost of arrow fields.
170.javascript-0170Mediummid

What do these try, catch, and finally puzzles print, and when does finally override a return or a thrown error?

A finally block always runs after try and catch, even after return, break, continue, or a thrown error. The return value is evaluated before finally runs, but a return, throw, break, or continue inside finally replaces the earlier result, which can swallow an error. In async functions finally runs after the awaited work, and in generators it runs when the iterator is closed early.

Full answer

Rules of try, catch, and finally:

  1. finally runs whatever happens: normal completion, return, throw, break, or continue in the try or catch.
  2. A return value is evaluated first and saved. Then finally runs. If finally does not return, the saved value is returned. So return x++ followed by changes to x in finally returns the old value of x. But changing an object that was returned changes the same object.
  3. If finally itself contains return, throw, break, or continue, it overrides the pending result. A return in finally discards a thrown error, which silently swallows the error, and it also overrides an earlier return. Lint rules (no-unsafe-finally) forbid this.
  4. An error thrown in finally replaces any pending error or return value.
  5. An error thrown in catch still lets finally run, and then propagates.
  6. catch without a binding (catch { ... }) is allowed when the error is not used.
  7. Nested try blocks: inner finally runs before the outer catch.
  8. In loops, continue or break in try still runs finally for that pass.
  9. In async functions: await inside try makes finally wait for it. A rejection that is caught by catch does not reach the caller. return promise without await inside a try does not catch its rejection in that function's catch, because the function leaves the try before the promise settles, while return await promise does catch it.
  10. In generators: when a consumer stops early with break or return(), the generator resumes at the paused yield as if a return happened, so its finally blocks run. That is how cleanup works for iterators.

Practical use: finally is for cleanup that must happen: closing files, releasing locks, hiding a loading spinner. Do not return from finally. If cleanup can throw, handle that error inside the cleanup so it does not replace the original one.

javascript
const attempt = (label, fn) => {
  try {
    console.log(label.padEnd(36), '->', fn());
  } catch (error) {
    console.log(label.padEnd(36), '->', 'threw', error.message);
  }
};
const order = [];

attempt('1. return value saved before finally', () => {
  let x = 1;
  try { return x++; } finally { x = 100; order.push('x is ' + x); }
});
attempt('1b. returned object is shared', () => {
  const o = { n: 1 };
  try { return o; } finally { o.n = 2; }
});
attempt('2. return in finally wins', () => {
  try { return 'from try'; } finally { return 'from finally'; }
});
attempt('3. return in finally swallows an error', () => {
  try { throw new Error('lost'); } finally { return 'swallowed'; }
});
attempt('4. throw in finally replaces return', () => {
  try { return 'value'; } finally { throw new Error('from finally'); }
});
attempt('5. error in catch, finally still runs', () => {
  try { throw new Error('first'); } catch (e) { throw new Error('from catch'); } finally { order.push('cleanup ran'); }
});
attempt('6. optional catch binding', () => {
  try { JSON.parse('{'); } catch { return 'ignored the error'; }
});
attempt('7. inner finally before outer catch', () => {
  const steps = [];
  try {
    try { throw new Error('boom'); } finally { steps.push('inner finally'); }
  } catch (e) { steps.push('outer catch ' + e.message); } finally { steps.push('outer finally'); }
  return steps.join(', ');
});
attempt('8. continue and break run finally', () => {
  const seen = [];
  for (let i = 0; i < 4; i++) {
    try {
      if (i === 1) continue;
      if (i === 3) break;
      seen.push('body ' + i);
    } finally { seen.push('finally ' + i); }
  }
  return seen.join(', ');
});
attempt('9. finally can override a break', () => {
  let count = 0;
  for (let i = 0; i < 3; i++) { try { break; } finally { count++; if (i < 2) continue; } }
  return count;
});
console.log(order);

function* resource() {
  try { yield 1; yield 2; yield 3; } finally { console.log('generator cleanup ran'); }
}
for (const value of resource()) { if (value === 2) break; }

async function plainReturn() { try { return Promise.reject(new Error('rejected')); } catch { return 'caught inside'; } }
async function awaitedReturn() { try { return await Promise.reject(new Error('rejected')); } catch { return 'caught inside'; } }
async function asyncFinally() {
  try { await new Promise((r) => setTimeout(r, 1)); return 'try finished'; } finally { console.log('async finally after the await'); }
}
(async () => {
  console.log('plain return:', await plainReturn().catch((e) => 'caller got ' + e.message));
  console.log('return await:', await awaitedReturn());
  console.log(await asyncFinally());
})();

Run with Node.js v24.22.1 as js-170.js; two runs gave identical output. Output: 1. return value saved before finally -> 1 1b. returned object is shared -> { n: 2 } 2. return in finally wins -> from finally 3. return in finally swallows an error -> swallowed 4. throw in finally replaces return -> threw from finally 5. error in catch, finally still runs -> threw from catch 6. optional catch binding -> ignored the error 7. inner finally before outer catch -> inner finally, outer catch boom, outer finally 8. continue and break run finally -> body 0, finally 0, finally 1, body 2, finally 2, finally 3 9. finally can override a break -> 3 [ 'x is 100', 'cleanup ran' ] generator cleanup ran plain return: caller got rejected return await: caught inside async finally after the await try finished

Key points

  • finally runs after try and catch in every case, including return, break, continue, and throw.
  • The return value is computed before finally; a return or throw inside finally replaces it and can swallow errors.
  • An error in catch or finally changes the outcome; inner finally runs before outer catch.
  • return await inside try catches rejections, plain return of a promise does not.
  • Generators run finally when closed early; use finally for cleanup, not for control flow.

Common mistakes

  • Returning from finally and silently swallowing errors.
  • Expecting changes to a returned primitive in finally to change the result.
  • Writing return promise inside try and expecting the catch to see its rejection.
  • Throwing from cleanup code in finally and hiding the original error.

Follow-ups

  • Why does a return in finally discard a thrown error?
  • How does return await differ from return inside a try block?
  • Which lint rule catches unsafe finally blocks?

Tips

  • State the rule: return is evaluated first, finally runs, and a jump in finally wins.
  • Show the async return await case, since it is a common production bug.
  • Say what finally is for: cleanup.
171.javascript-0171Mediummid

How do private class fields, private methods, and static initialization blocks work, and how are they different from the underscore convention?

A name starting with # declares a private field or method that only code written inside the class body can access. The rule is enforced by the language, so outside code, subclasses, Object.keys, and JSON.stringify cannot see it, and reading a missing one throws a TypeError. The syntax `#x in obj` checks whether an object has the private field. Static blocks run once when the class is defined, in order with static fields, so they can do multi-step setup.

Full answer

Private members use a # prefix: #count = 0;, #log() {}, static #instances = 0;. They are not properties. They live in a separate slot on the object, so obj['#count'], Object.keys(obj), JSON.stringify(obj), Reflect.ownKeys(obj), and for...in do not show them. Using obj.#count outside the class body is a SyntaxError at parse time, which is a stronger guarantee than the old _count naming convention, where anyone could still read and write the property.

Behaviors to know:

  • Each class that declares a private name has its own slot. A subclass cannot access a private field of its parent, even though the instance has it. The parent has to expose a method or accessor.
  • Reading a private field from an object that does not have it throws a TypeError. There is no undefined result. This is also true for a Proxy wrapping an instance: the proxy does not have the slot, so calling a method that uses private fields through a proxy can fail unless the method is bound to the target.
  • Brand checks: #field in obj returns true when obj was created by this class. It replaces instanceof-style duck typing for internal checks, and it works for objects from other realms.
  • Private methods and accessors (#compute(), get #value()) are installed once per class, not per instance, so they are cheaper than arrow-function fields.
  • Private fields are initialized in order of declaration, before the constructor body in a base class and right after super() returns in a derived class.
  • Private names are not available through reflection. Tests should check behavior through the public API instead.
  • static #x is private to the class itself, and this.#x in a static method called on a subclass fails, since this is the subclass. Use the class name: Counter.#x.

Static blocks, static { ... }, run once during class definition together with static fields, in source order. They are useful for multi-statement setup that does not fit one expression, for example building a lookup table, or filling a static registry that needs access to private static fields.

Trade-offs: private fields cannot be monkey-patched in tests, they are not copied by spread or structuredClone, and older runtimes need a transpiler. Use them for invariants that must not be broken, and keep plain properties for data that other code may read.

javascript
class Counter {
  static #created = 0;
  static registry = [];
  static {
    Counter.registry.push('static block ran, created = ' + Counter.#created);
  }

  #count = 0;
  label;

  constructor(label) {
    this.label = label;
    Counter.#created++;
  }

  #log(message) {
    return `[${this.label}] ${message}`;
  }

  increment() {
    this.#count++;
    return this.#log('count is ' + this.#count);
  }

  get value() {
    return this.#count;
  }

  static isCounter(candidate) {
    return #count in candidate;
  }

  static get created() {
    return Counter.#created;
  }
}

class LoudCounter extends Counter {
  shout() {
    return this.increment().toUpperCase();
  }
  peek() {
    try {
      return this['#count'];
    } catch (error) {
      return error.name;
    }
  }
}

const a = new Counter('a');
a.increment();
console.log(a.increment(), a.value);
console.log('keys:', Object.keys(a), 'ownKeys:', Reflect.ownKeys(a), 'json:', JSON.stringify(a));
console.log('property named #count:', a['#count']);
console.log('isCounter:', Counter.isCounter(a), Counter.isCounter({}), Counter.isCounter(new LoudCounter('b')));
console.log('registry:', Counter.registry);

const loud = new LoudCounter('loud');
console.log(loud.shout(), loud.peek(), Counter.created);

try {
  Counter.prototype.increment.call({});
} catch (error) {
  console.log('wrong object:', error.name);
}

const proxy = new Proxy(a, {});
try {
  proxy.increment();
} catch (error) {
  console.log('through a proxy:', error.name);
}
console.log('proxy with bound method:', Counter.prototype.increment.call(a));

try {
  new Function('class T { #secret = 1; } new T().#secret;');
} catch (error) {
  console.log('outside access at parse time:', error.name);
}
console.log('copy with spread:', { ...a });

Run with Node.js v24.22.1 as js-171.js; two runs gave identical output. Output: [a] count is 2 2 keys: [ 'label' ] ownKeys: [ 'label' ] json: {"label":"a"} property named #count: undefined isCounter: true false true registry: [ 'static block ran, created = 0' ] [LOUD] COUNT IS 1 undefined 3 wrong object: TypeError through a proxy: TypeError proxy with bound method: [a] count is 3 outside access at parse time: SyntaxError copy with spread: { label: 'a' }

Key points

  • #name members are language-enforced: invisible to keys, JSON, and reflection, and a SyntaxError outside the class.
  • Subclasses cannot access a parent's private fields; wrong-object access throws a TypeError.
  • #field in obj is a reliable brand check.
  • Private methods are shared per class; arrow fields are per instance.
  • Static blocks run once, in order with static fields, for multi-step setup.

Common mistakes

  • Expecting a subclass to read a parent's private field.
  • Wrapping instances in a Proxy and then calling methods that use private fields.
  • Relying on private fields for security, when they only protect against accidental access in the same program.
  • Testing private members directly instead of through public behavior.

Follow-ups

  • How does a private field differ from a closure variable in a factory function?
  • What does #x in obj give you that instanceof does not?
  • When would you prefer a WeakMap for private data?

Tips

  • Say the guarantee: language-enforced, not a naming convention.
  • Mention brand checks and the Proxy trap.
  • Explain that static blocks give multi-statement setup in class scope.
172.javascript-0172Mediummid

What are Error.cause and AggregateError, and how do you use them to keep the full story of a failure?

Passing { cause } as the second argument of an Error constructor links a low-level error to the higher-level one you throw, so wrapping an error does not lose the original stack or message. AggregateError holds many errors in its errors array, and Promise.any rejects with it when every promise fails. Log the whole chain, rethrow with context, and do not swallow the original.

Full answer

When code catches an error and throws a new one with a clearer message, the original error is often lost. Error.cause fixes that: new Error('Could not load profile', { cause: original }). The cause is stored as an own, non-enumerable property named cause, and it can be any value, not only an error. Each layer adds context for the reader of the log, while the root cause keeps its own stack.

Practical points:

  • Wrap at boundaries: a database layer throws a driver error, the service layer wraps it as "could not save order", and the HTTP layer converts it to a response. Logs should walk the chain through cause.
  • Custom errors should pass the options through: class AppError extends Error { constructor(message, options) { super(message, options); this.name = 'AppError'; } }.
  • cause is non-enumerable, so JSON.stringify(error) does not include it, and neither does { ...error }. Write a small serializer that walks the chain. Also protect against cycles.
  • AggregateError(errors, message) represents several failures at once. It has an errors array. Promise.any rejects with an AggregateError when all the input promises reject, and Promise.allSettled is the way to keep every result without a rejection.
  • Do not use cause for control flow. Use it for diagnosis, and match on error types or codes (error.code) for logic.
  • Browsers and Node.js print the cause when the error is logged with console.error, but custom log pipelines need to read the property.
  • The stack is a string created when the error is constructed, so create wrapping errors at the place of the failure, not in a helper that adds noise.

Avoid catching only to log and rethrow without adding information. Either add context with a cause, handle the error, or let it propagate.

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

function readConfig() {
  try {
    return JSON.parse('{ "port": ');
  } catch (error) {
    throw new AppError('Could not read the config', { cause: error });
  }
}

function startServer() {
  try {
    return readConfig();
  } catch (error) {
    throw new AppError('Server failed to start', { cause: error });
  }
}

function describe(error, seen = new Set()) {
  const chain = [];
  let current = error;
  while (current && !seen.has(current)) {
    seen.add(current);
    chain.push(`${current.name}: ${current.message}`);
    current = current.cause;
  }
  return chain;
}

try {
  startServer();
} catch (error) {
  console.log(describe(error).map((line, depth) => '  '.repeat(depth) + line).join('\n'));
  console.log('own keys:', Object.keys(error), 'has cause:', Object.hasOwn(error, 'cause'));
  console.log('json:', JSON.stringify(error));
  console.log('cause descriptor enumerable:', Object.getOwnPropertyDescriptor(error, 'cause').enumerable);
}

const plain = new Error('wrapped a string', { cause: 'just text' });
console.log('cause can be any value:', plain.cause);
console.log('no options, no property:', Object.hasOwn(new Error('x'), 'cause'));

const loop = new Error('a');
loop.cause = loop;
console.log('cycle protected:', describe(loop));

const fail = (name, delay) => new Promise((_, reject) => setTimeout(() => reject(new Error(name)), delay));
Promise.any([fail('first service', 3), fail('second service', 1)]).catch((error) => {
  console.log(error.constructor.name, '|', error.message, '|', error.errors.map((e) => e.message));
});

const manual = new AggregateError([new TypeError('bad type'), new RangeError('bad range')], 'Validation failed');
console.log(manual.name, manual.errors.length, manual.errors.map((e) => e.name));

Run with Node.js v24.22.1 as js-172.js; two runs gave identical output. Output: AppError: Server failed to start AppError: Could not read the config SyntaxError: Unexpected end of JSON input own keys: [ 'name' ] has cause: true json: {"name":"AppError"} cause descriptor enumerable: false cause can be any value: just text no options, no property: false cycle protected: [ 'Error: a' ] AggregateError 2 [ 'TypeError', 'RangeError' ] AggregateError | All promises were rejected | [ 'first service', 'second service' ]

Key points

  • new Error(message, { cause }) keeps the original error attached to the new one.
  • cause is non-enumerable, so serializers must read it explicitly and guard against cycles.
  • AggregateError holds an errors array; Promise.any rejects with it when all inputs fail.
  • Wrap errors at layer boundaries and match on type or code, not on message text.
  • Do not catch just to log and rethrow without context.

Common mistakes

  • Throwing a new error and losing the original one.
  • Expecting JSON.stringify or spread to copy cause, message, or stack.
  • Using Promise.all when every failure should be collected.
  • Matching on error messages instead of types or codes.

Follow-ups

  • How would you send an error with its cause chain to a logging service?
  • How does AggregateError differ from the result of Promise.allSettled?
  • Where should errors be wrapped in a layered application?

Tips

  • Say cause is for diagnosis, codes and types are for logic.
  • Mention that cause does not survive JSON.stringify.
  • Know that Promise.any rejects with AggregateError.
173.javascript-0173Easyfresher

What is a pure function, what counts as a side effect, and why do interviewers care?

A pure function always returns the same result for the same arguments and changes nothing outside itself. Side effects include mutating inputs or globals, reading time or randomness, logging, network calls, and touching the DOM. Pure functions are easy to test, cache, and reason about, so apps keep them at the center and push side effects to the edges.

Full answer

A function is pure when two conditions hold. First, the same input always gives the same output (it does not depend on hidden state such as a global variable, Date.now(), or Math.random()). Second, it causes no side effects: it does not change its arguments, global variables, the DOM, files, or the network, and it does not print anything.

Common impure things that surprise beginners:

  • array.sort(), reverse(), push(), and splice() mutate the array they are called on. Calling them on a parameter makes your function impure. Use toSorted, toReversed, slice, or spread to work on a copy.
  • Mutating an object parameter: user.active = true changes the caller's data.
  • Reading a variable from an outer scope that can change.
  • console.log is a side effect, even though it is usually harmless.
  • Returning a different result for the same input because of time or randomness.

Why it matters: pure functions are easy to unit test (no setup, no mocks), safe to cache with memoization, safe to run in any order or in parallel, and easy to debug because the output depends only on the input. Libraries such as Redux reducers and React render functions assume purity, and bugs appear when they are impure.

Programs still need side effects, because otherwise nothing would be displayed or saved. The usual design is a pure core with a thin impure shell: compute the new state with pure functions, then apply it to the screen or the server in one place. To keep a function pure while it needs time or randomness, pass them in as arguments, for example createId(random) or isExpired(date, now).

Interview tip: Object.freeze helps to detect mutation but is shallow, and purity is a design rule, not something the language checks.

javascript
'use strict';
let taxRate = 0.2;

const impureTotal = (price) => price * (1 + taxRate);
const pureTotal = (price, rate) => price * (1 + rate);

function impureSortNames(names) {
  return names.sort();
}
function pureSortNames(names) {
  return [...names].sort();
}

function impureActivate(user) {
  user.active = true;
  return user;
}
function pureActivate(user) {
  return { ...user, active: true };
}

console.log(impureTotal(100));
taxRate = 0.5;
console.log(impureTotal(100), 'same input, different output');
console.log(pureTotal(100, 0.2), pureTotal(100, 0.2));

const names = ['Maya', 'Ben', 'Asha'];
const sortedCopy = pureSortNames(names);
console.log(sortedCopy, names);
const sortedInPlace = impureSortNames(names);
console.log(sortedInPlace === names, names);

const user = Object.freeze({ id: 1, active: false });
console.log(pureActivate(user), user);
try {
  impureActivate(user);
} catch (error) {
  console.log('frozen input exposes the mutation:', error.name);
}

const isExpired = (expiresAt, now) => now >= expiresAt;
console.log(isExpired(1000, 999), isExpired(1000, 1000));

const createId = (random) => 'id-' + Math.floor(random * 1000);
console.log(createId(0.123), createId(0.123));

const pureSteps = [1, 2, 3, 4].filter((n) => n % 2 === 0).map((n) => n * 10);
console.log(pureSteps);

Run with Node.js v24.22.1 as js-173.js; two runs gave identical output. Output: 120 150 same input, different output 120 120 [ 'Asha', 'Ben', 'Maya' ] [ 'Maya', 'Ben', 'Asha' ] true [ 'Asha', 'Ben', 'Maya' ] { id: 1, active: true } { id: 1, active: false } frozen input exposes the mutation: TypeError false true id-123 id-123 [ 20, 40 ]

Key points

  • Pure: same input, same output, and no effect outside the function.
  • Side effects: mutating inputs or globals, time, randomness, I/O, logging, and the DOM.
  • Copy before using sort, reverse, push, and splice on parameters.
  • Pure code is easier to test, memoize, and run in parallel.
  • Use a pure core and an impure shell; pass time and randomness in as arguments.

Common mistakes

  • Calling sort or reverse on a parameter and thinking that no data changes.
  • Using Date.now or Math.random inside a function that should be pure.
  • Thinking Object.freeze makes nested objects immutable.
  • Believing that all side effects are bad, instead of controlling where they happen.

Follow-ups

  • Why must a Redux reducer be pure?
  • How do you test code that uses the current time?
  • Is a function that logs to the console pure?

Tips

  • Give the two-part definition and an example of each part.
  • Show a sort on a parameter as the typical hidden mutation.
  • End with the pure core and impure shell idea.
174.javascript-0174Mediummid

Where does rendering fit into the browser event loop, and how do microtasks, timers, and requestAnimationFrame relate to a frame?

The browser runs one task, then all microtasks, and then it may run a rendering step if a frame is due, which includes requestAnimationFrame callbacks, style, layout, and paint. Microtasks always finish before the browser can paint, while timers are tasks that run between frames. A long task or an endless microtask chain blocks painting and input, so split work and yield.

Full answer

The browser's event loop repeats this cycle. Pick one task from a task queue (a click, a timer callback, a network event, a script). Run it to completion. Run all queued microtasks (promise callbacks and queueMicrotask) until the queue is empty. Then, if the browser decides a frame is due (typically every 16.7 ms at 60 Hz, and only when the page is visible), it runs the rendering steps: requestAnimationFrame callbacks, then style calculation, layout, and paint.

What follows from this:

  • Rendering cannot happen while JavaScript runs. A task that takes 200 ms blocks about 12 frames, input handling, and animations, which users feel as jank. Chrome reports tasks over 50 ms as long tasks.
  • Microtasks run before the next paint, so a state change made in a promise callback and another one made in the same task are painted together. An endless chain of microtasks starves rendering and timers.
  • setTimeout(fn, 0) queues a task. It runs after the current task and its microtasks, but the browser may or may not render in between, so it is not a promise of a frame. Timers also have a minimum delay (about 4 ms after nesting) and are clamped in background tabs.
  • requestAnimationFrame runs right before the next paint, which makes it the right place for visual updates such as reading layout and then writing styles, and for animation steps. Two updates in one frame are painted once.
  • Reading layout values (offsetHeight) after writing styles forces a synchronous layout, which is called layout thrashing. Batch reads before writes.
  • To keep the page responsive, split long work into chunks and yield between them. Options are setTimeout, scheduler.postTask or scheduler.yield where available, requestIdleCallback for low priority work, and Web Workers for heavy computation.
  • await of an already resolved value still yields only to the microtask queue, so it does not give the browser a chance to paint.

A common interview question: "Why does the loading text not appear before the loop starts?" Because the text change is only painted in the rendering step, which cannot happen until the synchronous loop and its microtasks have finished. Yield with a timer or a rAF plus a timer, then start the work.

javascript
// A small model of the loop, not a browser. It makes the order visible and repeatable.
function createLoop() {
  const tasks = [];
  const microtasks = [];
  const log = [];
  let frame = 0;
  const loop = {
    log,
    task: (name, fn) => tasks.push({ name, fn }),
    microtask: (fn) => microtasks.push(fn),
    raf: [],
    run(frameEveryNTasks) {
      let ran = 0;
      while (tasks.length) {
        const { name, fn } = tasks.shift();
        log.push('task ' + name);
        fn();
        while (microtasks.length) microtasks.shift()();
        ran++;
        if (ran % frameEveryNTasks === 0) {
          frame++;
          log.push(`--- frame ${frame}: rAF x${loop.raf.length}, then style, layout, paint`);
          const callbacks = loop.raf.splice(0);
          callbacks.forEach((cb) => cb());
        }
      }
    },
  };
  return loop;
}

const loop = createLoop();
loop.task('A (script)', () => {
  loop.log.push('  sync code in A');
  loop.microtask(() => loop.log.push('  microtask from A'));
  loop.raf.push(() => loop.log.push('  rAF callback'));
  loop.task('B (setTimeout 0)', () => {
    loop.log.push('  sync code in B');
    loop.microtask(() => loop.log.push('  microtask from B'));
  });
});
loop.task('C (click)', () => loop.log.push('  sync code in C'));
loop.run(2);
console.log(loop.log.join('\n'));

// The real engine proves the first part of the model: microtasks run before the next task.
const real = [];
setTimeout(() => real.push('timer task'), 0);
Promise.resolve().then(() => real.push('promise microtask'));
queueMicrotask(() => real.push('queueMicrotask'));
real.push('sync');
setTimeout(() => console.log('real engine order:', real.join(' > ')), 5);

Run with Node.js v24.22.1 as js-174.js; two runs gave identical output. Output: task A (script) sync code in A microtask from A task C (click) sync code in C --- frame 1: rAF x1, then style, layout, paint rAF callback task B (setTimeout 0) sync code in B microtask from B real engine order: sync > promise microtask > queueMicrotask > timer task

Key points

  • Cycle: one task, all microtasks, then possibly a render step with rAF, style, layout, and paint.
  • Nothing paints while JavaScript runs, so long tasks cause jank and unresponsive input.
  • Microtasks finish before paint; endless microtasks starve rendering and timers.
  • setTimeout 0 is a task, not a frame; use rAF for visual updates.
  • Chunk work and yield with timers, scheduler APIs, idle callbacks, or workers.

Common mistakes

  • Expecting the page to update during a long synchronous loop.
  • Using setTimeout 0 as if it guaranteed a repaint.
  • Doing visual updates in timers instead of requestAnimationFrame.
  • Alternating style writes and layout reads, which forces repeated layouts.

Follow-ups

  • How does scheduler.yield differ from setTimeout for splitting work?
  • Why can a promise chain block painting?
  • How do you find long tasks in a real page?

Tips

  • Draw the loop as task, microtasks, render.
  • Use the loading text example to show why yielding is needed.
  • Name rAF as the place for visual updates.
175.javascript-0175Hardsenior

What is microtask starvation, how can it happen with promises or process.nextTick, and how do you yield to the event loop?

The event loop drains the whole microtask queue before it moves on, so a microtask that keeps scheduling another one means timers, I/O, input, and painting never get a turn. process.nextTick in Node.js is even earlier than promise callbacks. The fix is to process work in chunks and yield through a task, such as setTimeout, setImmediate, or scheduler.yield, so other work can run between chunks.

Full answer

After each task, the engine runs microtasks until the queue is empty, including microtasks that were added while draining. If every microtask adds another one, the queue never empties. The event loop is stuck in the microtask phase: timers do not fire, network callbacks wait, and in a browser there is no paint or input handling. The page freezes, although the code is "asynchronous".

How it happens in practice:

  • A recursive promise chain or an async function that loops with await on an already resolved value, for example polling a cache that returns immediately. await on a settled promise only continues in a microtask.
  • A recursive queueMicrotask.
  • In Node.js, process.nextTick callbacks run before promise microtasks, and a recursive nextTick also starves everything else. Node.js limits nothing by default.
  • A retry or drain loop with no real asynchronous boundary.

Timing detail: a promise callback is a microtask, setTimeout and setImmediate callbacks are tasks (macrotasks) in the timers and check phases in Node.js, and I/O callbacks have their own phase. Microtasks run after each callback, in every phase.

Fixes:

  1. Process work in bounded chunks and yield to a real task between them: await new Promise((r) => setTimeout(r)), setImmediate in Node.js, and scheduler.yield() or scheduler.postTask() in browsers that support them, with MessageChannel as a common fallback.
  2. Put heavy CPU work in a worker thread or Web Worker.
  3. For polling, use a real wait or an event instead of a loop of resolved promises.
  4. Use a time budget per chunk (for example 5 ms) rather than an item count, so the chunk size adapts to the machine.

A related design point: yielding has a cost, so do not yield on every item. Yield about every few milliseconds of work. Also make the work cancellable between chunks with an AbortSignal.

Interview angle: explain that "async" does not mean "does not block"; only tasks give other work a chance, and microtasks only give other microtasks a chance.

javascript
const events = [];
const TOTAL = 50000;

function starving() {
  return new Promise((resolve) => {
    let count = 0;
    const step = () => {
      if (++count < TOTAL) queueMicrotask(step);
      else {
        events.push(`starving work done, ${count} microtasks`);
        resolve();
      }
    };
    queueMicrotask(step);
  });
}

function chunked() {
  return new Promise((resolve) => {
    let count = 0;
    const CHUNK = 10000;
    const step = () => {
      const stop = Math.min(count + CHUNK, TOTAL);
      while (count < stop) count++;
      events.push(`chunk finished at ${count}`);
      if (count < TOTAL) setImmediate(step);
      else resolve();
    };
    step();
  });
}

(async () => {
  setImmediate(() => events.push('immediate A ran'));
  await starving();
  await new Promise((resolve) => setImmediate(resolve));
  events.push('--- now the chunked version ---');

  setImmediate(() => events.push('immediate B ran'));
  await chunked();
  await new Promise((resolve) => setImmediate(resolve));
  console.log(events.join('\n'));

  const order = [];
  setImmediate(() => order.push('setImmediate'));
  Promise.resolve().then(() => order.push('promise'));
  process.nextTick(() => order.push('nextTick'));
  queueMicrotask(() => order.push('queueMicrotask'));
  order.push('sync');
  await new Promise((resolve) => setTimeout(resolve, 5));
  console.log(order.join(' > '));
})();

Run with Node.js v24.22.1 as js-175.js; two runs gave identical output. Output: starving work done, 50000 microtasks immediate A ran --- now the chunked version --- chunk finished at 10000 immediate B ran chunk finished at 20000 chunk finished at 30000 chunk finished at 40000 chunk finished at 50000 sync > promise > queueMicrotask > nextTick > setImmediate

Key points

  • The microtask queue is drained completely, including newly added microtasks, before the next task.
  • Recursive promises, awaits on settled values, queueMicrotask, and process.nextTick can starve timers, I/O, and painting.
  • process.nextTick runs before promise callbacks in Node.js.
  • Yield through a task (setTimeout, setImmediate, scheduler.yield) between chunks.
  • Use a time budget for each chunk, a worker for heavy work, and cancellation between chunks.

Common mistakes

  • Believing that async code can never block the page.
  • Looping on await of an already resolved promise.
  • Yielding with another promise, which does not give timers or paint a turn.
  • Yielding on every item, which makes the work much slower.

Follow-ups

  • How would you cancel a chunked job halfway?
  • What is the difference between process.nextTick and queueMicrotask?
  • How does scheduler.yield differ from setTimeout 0?

Tips

  • State that only a task lets other work run.
  • Mention the nextTick before promise order in Node.js.
  • Suggest a time budget per chunk instead of a fixed item count.
176.javascript-0176Hardsenior

What is a realm in JavaScript, and why do instanceof checks fail for objects that come from an iframe or a vm context?

A realm is a full set of built-in objects, such as its own Array, Object, and Error constructors with their own prototypes, plus a global object. An iframe, a vm context, or a worker has a different realm, so an array made there is a real array but is not an instance of your Array. Use realm-independent checks such as Array.isArray, Object.prototype.toString, or private brand checks.

Full answer

Each global environment has its own copy of the standard library. A page and an iframe each have an Array, Object, Error, Promise, and Map, and their prototypes are different objects. Node.js vm contexts behave the same way. Objects can cross the border freely, because they are just references, but their prototype chains still point to the original realm.

Consequences:

  • otherArray instanceof Array is false, because Array.prototype of your realm is not in the chain of an array from another realm. The same happens for Error, Date, RegExp, Map, and Promise.
  • Array.isArray(x) works across realms, because it checks the internal type of the object, not its prototype. The same idea applies to Object.prototype.toString.call(x) (it reads Symbol.toStringTag or the internal class) and to Number.isFinite.
  • For typed or special objects in Node.js, util.types.isDate, isRegExp, isPromise, and isNativeError are safe. In browsers, Error.isError is still new, so check Object.prototype.toString or the name property when you accept errors from other frames.
  • Primitive values are not realm specific. Symbol.for('key') returns the same symbol in all realms, and well-known symbols such as Symbol.iterator are shared too, while a symbol made with Symbol('key') is unique.
  • A function from another realm has another Function.prototype, so fn instanceof Function can be false even though typeof fn === 'function' is true. typeof is realm safe.
  • Errors thrown by built-ins use the realm of the function that was called, not the caller. A TypeError from a method of an iframe's array is the iframe's TypeError.
  • Private class fields are per class definition, so #field in obj works across realms only when the same class is used, and it fails for another copy of the class loaded in another realm.
  • Two copies of a library, for example loaded in two frames, produce classes that fail each other's instanceof checks.

Practical guidance: libraries that accept user input should avoid instanceof for built-ins and use Array.isArray, typeof, duck typing, or tag checks. Symbol.hasInstance can customize instanceof. structuredClone and postMessage copy values into the receiver's realm, which removes the mismatch.

Realms are also the base of sandboxing proposals (ShadowRealm) and of test runners that run code in separate contexts. Test frameworks sometimes fail for this reason: expect(result).toBeInstanceOf(Array) can fail when result came from a vm context.

javascript
const vm = require('node:vm');
const util = require('node:util');

const foreign = vm.runInNewContext('({ list: [1, 2, 3], when: new Date(0), fail: new TypeError("other"), fn: function () {}, sym: Symbol.for("shared"), local: Symbol("local") })');

console.log('Array.isArray:', Array.isArray(foreign.list));
console.log('instanceof Array:', foreign.list instanceof Array);
console.log('toString tag:', Object.prototype.toString.call(foreign.list));
console.log('same prototype:', Object.getPrototypeOf(foreign.list) === Array.prototype);
console.log('constructor name still matches:', foreign.list.constructor.name === 'Array', foreign.list.constructor === Array);

console.log('Date instanceof:', foreign.when instanceof Date, 'util.types.isDate:', util.types.isDate(foreign.when));
console.log('Error instanceof:', foreign.fail instanceof Error, 'util.types.isNativeError:', util.types.isNativeError(foreign.fail));
console.log('function: typeof =', typeof foreign.fn, ', instanceof Function =', foreign.fn instanceof Function);
console.log('Symbol.for shared:', foreign.sym === Symbol.for('shared'), '| plain symbol shared:', foreign.local === Symbol('local'));

const cloned = structuredClone(foreign.list);
console.log('structuredClone into this realm:', cloned instanceof Array);

console.log('spread into a local array:', [...foreign.list] instanceof Array, Array.from(foreign.list) instanceof Array);

class Even {
  static [Symbol.hasInstance](value) {
    return Array.isArray(value) && value.length % 2 === 0;
  }
}
console.log('custom hasInstance, foreign array of 3:', foreign.list instanceof Even, ', of 2:', [1, 2] instanceof Even);

const text = vm.runInNewContext('typeof String(1) + typeof Object(1)');
console.log('primitives are realm neutral:', text);

Run with Node.js v24.22.1 as js-176.js; two runs gave identical output. Output: Array.isArray: true instanceof Array: false toString tag: [object Array] same prototype: false constructor name still matches: true false Date instanceof: false util.types.isDate: true Error instanceof: false util.types.isNativeError: true function: typeof = function , instanceof Function = false Symbol.for shared: true | plain symbol shared: false structuredClone into this realm: true spread into a local array: true true custom hasInstance, foreign array of 3: false , of 2: true primitives are realm neutral: stringobject

Key points

  • A realm is a global object plus its own built-in constructors and prototypes.
  • instanceof fails across realms; Array.isArray, typeof, and toString tags work.
  • Symbol.for is shared across realms, while a constructor-created class is not.
  • Errors and objects from built-ins belong to the realm of the called function.
  • Prefer realm-safe checks in libraries and use structuredClone or postMessage to copy into your realm.

Common mistakes

  • Using instanceof Array, Error, or Date on data that may come from another frame or context.
  • Assuming typeof and instanceof Function agree.
  • Loading two copies of one library and comparing their classes.
  • Using instanceof in test assertions across vm contexts.

Follow-ups

  • What does structuredClone do to the prototype of an object?
  • How does Symbol.hasInstance change the behavior of instanceof?
  • Where do you see realms in test runners or sandboxes?

Tips

  • Start with the iframe example, then name the realm-safe checks.
  • Mention Array.isArray and Symbol.for as the cross-realm safe tools.
  • Know that errors belong to the realm of the called function.
177.javascript-0177Hardsenior

Why do the specification and engine authors advise against relying on WeakRef and FinalizationRegistry, and what are they safe to use for?

A WeakRef lets an object be collected, but when that happens is up to the engine, so code must work when collection never happens and when it happens at any point between turns. An object stays alive for the rest of the current job once you deref it, and finalization callbacks may run late or never. Use them only for optional optimization such as caches, never for correctness or required cleanup.

Full answer

new WeakRef(target) holds the target without keeping it alive. ref.deref() returns the target, or undefined if it was collected. FinalizationRegistry lets you register a callback that may run after a target was collected, with a held value you chose.

The guarantees are weak on purpose:

  • There is no guarantee that a collection happens at all. A short script, a small heap, or an engine choice means the target may live until the process exits. Callbacks might never run.
  • Within one synchronous job, a target that was returned from deref() or created is kept alive until the end of that job. That keeps program behavior consistent: ref.deref() === ref.deref() is true within one turn. So tests that create, drop, and check in the same turn never see a collection.
  • Finalization callbacks run in a separate task after collection, with no promised delay and no promised order. The target is gone when the callback runs, which is why you can only use the held value, and the held value must not reference the target or it keeps the target alive.
  • The behavior differs between engines, versions, and settings, and also between a debug run and production. Code that passes locally can fail in production.
  • Cycles through the registry or held values leak. Unregister tokens help you stop callbacks when you clean up by hand.
  • WeakRef can only target objects and non-registered symbols. A string, number, or Symbol.for symbol throws a TypeError.

Good uses: an optional cache where the value can be rebuilt (WeakRef to a parsed result keyed by a string), mapping DOM nodes to expensive data when a WeakMap is not enough because you need to iterate, and leak detection in tests (with --expose-gc and a wait).

Bad uses: closing file handles, sockets, or locks (use try/finally, using, or explicit close()), counting live objects for business logic, and releasing external resources that must be freed at a known time.

A WeakMap is the better first choice when you just need to attach data to an object without keeping it alive. Reach for WeakRef only for the case that needs a key that is a string, such as a cache keyed by id.

javascript
const registry = new FinalizationRegistry((held) => finalized.push(held));
const finalized = [];
const tick = () => new Promise((resolve) => setTimeout(resolve, 20));

function makeCache() {
  const refs = new Map();
  return {
    set(key, value) {
      refs.set(key, new WeakRef(value));
    },
    get(key) {
      const value = refs.get(key)?.deref();
      if (value === undefined) refs.delete(key);
      return value;
    },
    size: () => refs.size,
  };
}

(async () => {
  let target = { big: new Array(1000).fill('data') };
  const ref = new WeakRef(target);
  registry.register(target, 'target was collected');

  console.log('same turn, deref twice is stable:', ref.deref() === ref.deref());
  target = null;
  global.gc();
  console.log('same turn after gc, still alive:', ref.deref() !== undefined);

  await tick();
  global.gc();
  await tick();
  console.log('later turn after gc, collected:', ref.deref() === undefined);
  console.log('finalizer ran later:', finalized);

  const cache = makeCache();
  cache.set('user:1', { name: 'Asha' });
  console.log('cache size before gc:', cache.size());
  await tick();
  global.gc();
  await tick();
  console.log('cache lookup after gc:', cache.get('user:1'), '| size:', cache.size());

  for (const bad of ['text', 42, Symbol.for('registered')]) {
    try {
      new WeakRef(bad);
    } catch (error) {
      console.log('WeakRef of', typeof bad, '->', error.name);
    }
  }
  console.log('WeakRef of a local symbol works:', new WeakRef(Symbol('local')).deref() !== undefined);
})();

Run with Node.js v24.22.1 using the --expose-gc flag as js-177.js; two runs gave identical output. Output: same turn, deref twice is stable: true same turn after gc, still alive: true later turn after gc, collected: true finalizer ran later: [ 'target was collected' ] cache size before gc: 1 cache lookup after gc: undefined | size: 0 WeakRef of string -> TypeError WeakRef of number -> TypeError WeakRef of symbol -> TypeError WeakRef of a local symbol works: true

Key points

  • Collection time is not guaranteed and may never happen; code must stay correct either way.
  • A deref'd or created target stays alive until the end of the current job.
  • Finalization callbacks are late, unordered, and optional; the held value must not reference the target.
  • Safe for optional caches and diagnostics, never for required cleanup.
  • Prefer WeakMap for attaching data; use try/finally or explicit close for resources.

Common mistakes

  • Using FinalizationRegistry to release resources that must be released.
  • Testing collection in the same synchronous turn, where the target is kept alive.
  • Holding the target inside the held value, which keeps it alive forever.
  • Using WeakRef where a WeakMap would be simpler and safer.

Follow-ups

  • How does a WeakMap differ from a Map of WeakRefs?
  • What does the unregister token do?
  • How would you test for a memory leak in a unit test?

Tips

  • Lead with "no guarantee it ever happens".
  • Mention the keep-alive until the end of the job rule.
  • Offer WeakMap, explicit close, and try/finally as the better tools.
178.javascript-0178Mediummid

How do extends, super, and new.target work in class inheritance, and what are the common traps?

extends links both the prototype chain of instances and the constructor chain of the classes. A derived constructor must call super() before it touches this, because the parent constructor creates the object. super.method() calls the parent version using the home object, and new.target tells a constructor which class was called with new, which is how abstract classes are written. Extending built-ins works and keeps their special behavior.

Full answer

class B extends A sets two links: B.prototype.__proto__ === A.prototype for instance methods, and B.__proto__ === A so that static members are inherited too.

Construction rules:

  • In a base class, new creates the object and the constructor initializes it. In a derived class the object is created by the parent constructor, so you must call super(...) before reading or writing this, otherwise you get a ReferenceError. If a derived class has no constructor, the default one passes all arguments to super.
  • A constructor may return an object, which replaces this. Returning a primitive is ignored, and a derived constructor that returns a primitive other than undefined throws.
  • Class fields of the derived class are initialized right after super() returns, so a parent constructor that calls an overridden method will see the derived fields as undefined. Do not call overridable methods from constructors.
  • super.method() looks up the method on the parent prototype but calls it with the current this. It works in object literal methods too, because it uses the method's home object, but not in plain functions or arrow functions that are not inside a method.
  • new.target is the constructor that was invoked with new, and is undefined in a normal call. In a parent constructor it is the derived class, so if (new.target === Shape) throw ... makes an abstract class, and a factory can pick behavior by new.target.name.
  • extends null creates a class whose instances have no Object.prototype, and it cannot be constructed without a custom return.
  • Extending built-ins works: class Stack extends Array. Methods such as map and filter create the result through Symbol.species, so they return a Stack. Override static get [Symbol.species]() { return Array; } to return a plain array. class MyError extends Error needs super(message) and sets name explicitly.
  • instanceof checks the prototype chain, and a method defined on the parent is found by lookup at call time, so changing the parent prototype later affects all children.

Alternative to remember: deep hierarchies are hard to change. Prefer composition for sharing behavior, and use inheritance for real is-a relationships with a stable parent.

javascript
class Shape {
  constructor(name) {
    if (new.target === Shape) throw new TypeError('Shape is abstract');
    this.name = name;
    console.log(`  Shape constructor, new.target is ${new.target.name}, describe() gives: ${this.describe()}`);
  }
  area() {
    throw new Error(`${this.constructor.name} must implement area`);
  }
  describe() {
    return `${this.name} with area ${this.area().toFixed(2)}`;
  }
  static create(...args) {
    return new this(...args);
  }
}

class Circle extends Shape {
  radius = 1;
  constructor(radius) {
    super('circle');
    this.radius = radius;
  }
  area() {
    return Math.PI * (this.radius ?? 0) ** 2;
  }
  describe() {
    return 'round ' + super.describe();
  }
}

console.log('abstract:', (() => { try { return new Shape('x'); } catch (e) { return e.message; } })());
const circle = Circle.create(2);
console.log(circle.describe());
console.log('prototype links:', Object.getPrototypeOf(Circle) === Shape, Object.getPrototypeOf(Circle.prototype) === Shape.prototype);

class Broken extends Shape {
  constructor() {
    this.x = 1;
    super('broken');
  }
}
try { new Broken(); } catch (e) { console.log('this before super:', e.name); }

class Returns extends Shape {
  constructor() {
    super('returns');
    return { replaced: true };
  }
  area() { return 1; }
}
console.log('constructor returning an object:', new Returns());

class Stack extends Array {
  peek() { return this[this.length - 1]; }
}
const stack = Stack.from([1, 2, 3]);
console.log('map keeps the subclass:', stack.map((n) => n * 2) instanceof Stack, stack.peek(), stack.length);
class PlainStack extends Array {
  static get [Symbol.species]() { return Array; }
}
console.log('species override:', PlainStack.from([1]).map((n) => n) instanceof PlainStack);

const base = { hello() { return 'base hello'; } };
const child = { __proto__: base, hello() { return 'child then ' + super.hello(); } };
console.log(child.hello());

function plain() { return new.target === undefined ? 'called without new' : 'called with new'; }
console.log(plain(), '|', new plain() instanceof plain);

Run with Node.js v24.22.1 as js-178.js; two runs gave identical output. Output: abstract: Shape is abstract Shape constructor, new.target is Circle, describe() gives: round circle with area 0.00 round circle with area 12.57 prototype links: true true this before super: ReferenceError Shape constructor, new.target is Returns, describe() gives: returns with area 1.00 constructor returning an object: { replaced: true } map keeps the subclass: true 3 3 species override: false child then base hello called without new | true

Key points

  • extends links instance prototypes and class constructors, so static members are inherited.
  • Call super() before using this in a derived constructor; field initializers run right after it.
  • super.method() uses the home object but the current this.
  • new.target names the class called with new; use it for abstract classes.
  • Built-in subclasses work, and Symbol.species controls the type of derived results.

Common mistakes

  • Using this before super() in a derived constructor.
  • Calling overridable methods from a base constructor and reading uninitialized derived fields.
  • Forgetting that arrow functions and plain functions cannot use super.
  • Building deep hierarchies where composition would be simpler.

Follow-ups

  • What does Symbol.species do and when would you override it?
  • How would you implement an abstract method check?
  • How do static methods get inherited?

Tips

  • Describe the two prototype links, instance and static.
  • Explain why super() comes first: the parent creates the object.
  • Mention the constructor-calls-override trap.
179.javascript-0179Hardsenior

How do you compose cancellation with AbortSignal.any and AbortSignal.timeout, and how do you clean up correctly?

Create one controller per operation, combine the user's signal with AbortSignal.timeout(ms) using AbortSignal.any, pass the combined signal down, and read signal.reason to tell a timeout from a cancel. Check signal.throwIfAborted() between steps, remove listeners in finally, and make abortable helpers reject with the reason so callers can handle both cases separately.

Full answer

An AbortSignal is a one-way notification. A controller aborts, and any number of listeners react. Composition is the interesting part:

  • AbortSignal.timeout(ms) gives a signal that aborts with a TimeoutError after the delay. controller.abort() without a reason uses an AbortError. You can pass any reason: controller.abort(new Error('user left')).
  • AbortSignal.any([a, b]) returns a signal that aborts when the first input aborts, and carries that input's reason. This is how you combine a caller's signal, a timeout, and a component lifecycle signal without writing glue code. Older runtimes need a small helper with listeners.
  • signal.throwIfAborted() is the simple checkpoint between steps of a long operation. signal.aborted and signal.reason expose the state.
  • A helper such as sleep(ms, { signal }) should reject with signal.reason, not with a new generic error, so callers can tell TimeoutError from a user cancel. It must also check signal.aborted first, because an already aborted signal never fires the event again.
  • Always remove the abort listener when the operation finishes normally ({ once: true } plus removeEventListener in finally). Otherwise a long-lived signal collects listeners and keeps the closures alive.
  • Cancellation is cooperative. Aborting does not stop code that never checks the signal. fetch and many Node.js APIs accept signal, and your own functions need to pass it on.
  • Design for partial work: abort can happen at any await. Keep operations idempotent or rollback in catch and finally.
  • Separate three outcomes in the caller: success, aborted by the user (often not an error to report), and timed out (often retried or reported). Check error === signal.reason or error.name.

Pattern for APIs: accept { signal } options, never create a controller you do not own, and document which reason you reject with.

javascript
function sleep(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const onAbort = () => {
      clearTimeout(timer);
      reject(signal.reason);
    };
    const timer = setTimeout(() => {
      signal?.removeEventListener('abort', onAbort);
      resolve();
    }, ms);
    signal?.addEventListener('abort', onAbort, { once: true });
  });
}

async function runJob(name, steps, { signal, timeoutMs }) {
  const combined = timeoutMs ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)].filter(Boolean)) : signal;
  const done = [];
  try {
    for (let i = 1; i <= steps; i++) {
      combined?.throwIfAborted();
      await sleep(40, { signal: combined });
      done.push(i);
    }
    return `${name}: finished ${done.length} steps`;
  } catch (error) {
    const kind = error.name === 'TimeoutError' ? 'timed out' : error.name === 'AbortError' ? 'cancelled by user' : 'failed';
    return `${name}: ${kind} after ${done.length} steps (${error.name})`;
  }
}

(async () => {
  console.log(await runJob('normal', 2, { timeoutMs: 1000 }));

  console.log(await runJob('timeout', 10, { timeoutMs: 100 }));

  const user = new AbortController();
  setTimeout(() => user.abort(), 100);
  console.log(await runJob('user cancel', 10, { signal: user.signal, timeoutMs: 2000 }));

  const custom = new AbortController();
  custom.abort(new Error('component unmounted'));
  console.log(await runJob('custom reason', 3, { signal: custom.signal }));

  const early = AbortSignal.abort();
  console.log('already aborted signal rejects at once:', await sleep(10, { signal: early }).catch((e) => e.name));

  const first = new AbortController();
  const second = new AbortController();
  const any = AbortSignal.any([first.signal, second.signal]);
  second.abort(new Error('second wins'));
  first.abort(new Error('first is too late'));
  console.log('any keeps the first reason:', any.reason.message);

  const controller = new AbortController();
  let listeners = 0;
  const count = () => listeners++;
  controller.signal.addEventListener('abort', count, { once: true });
  controller.abort();
  controller.abort();
  console.log('abort fires once:', listeners, '| reason name:', controller.signal.reason.name);
})();

Run with Node.js v24.22.1 as js-179.js; two runs gave identical output. Output: normal: finished 2 steps timeout: timed out after 2 steps (TimeoutError) user cancel: cancelled by user after 2 steps (AbortError) custom reason: failed after 0 steps (Error) already aborted signal rejects at once: AbortError any keeps the first reason: second wins abort fires once: 1 | reason name: AbortError

Key points

  • AbortSignal.timeout gives TimeoutError; AbortSignal.any combines signals and keeps the reason of the first one.
  • Helpers should check signal.aborted first and reject with signal.reason.
  • Use throwIfAborted between steps and remove listeners in finally.
  • Cancellation is cooperative; pass the signal to everything inside.
  • Tell success, user abort, and timeout apart in the caller.

Common mistakes

  • Rejecting with a generic error and losing the reason.
  • Forgetting to check signal.aborted before adding the listener.
  • Leaving abort listeners attached to a long-lived signal.
  • Reporting a user cancel as a failure.

Follow-ups

  • How would you build a signal that aborts when a component unmounts?
  • How does fetch react to an aborted signal after the headers arrived?
  • How would you implement AbortSignal.any in an older runtime?

Tips

  • Show the three outcomes: done, cancelled, timed out.
  • Mention listener cleanup and cooperative cancellation.
  • Pass the signal down to every async step.
180.javascript-0180Mediummid

How does a virtual list (windowing) work, and how would you implement the visible range calculation for a fixed row height?

A virtual list renders only the rows near the viewport inside a tall container whose height is the full list size, so the scrollbar behaves normally. On scroll, compute the first and last visible index from scrollTop, viewport height, and row height, add an overscan buffer, and position the rendered rows with padding or transforms. This keeps the DOM small for lists with tens of thousands of items.

Full answer

Rendering 50,000 rows creates 50,000 elements and makes layout, style, and memory usage slow. Windowing renders only what the user can see.

Core idea for fixed row height h, viewport height V, and scrollTop s:

  • start = Math.floor(s / h) and end = Math.ceil((s + V) / h).
  • Add overscan rows above and below (for example 5) to avoid blank areas during fast scrolling, and clamp to [0, count].
  • Total height is count * h. Use a top spacer of start * h and a bottom spacer of (count - end) * h, or absolute positioning with transform: translateY(...). The scrollbar then matches the full list.
  • On scroll, recompute the range. Only re-render when the range changes, and batch the work in requestAnimationFrame. Scroll events are frequent, so make the handler passive and cheap.
  • Reuse DOM nodes where possible (recycling), and use stable keys when a framework renders the rows.

Harder parts for follow-up discussion:

  • Variable row heights: measure rendered rows with ResizeObserver, store heights in an array, keep a prefix-sum array and find the start with binary search, and use an estimated height for unmeasured rows. Scroll position jumps when estimates are corrected, so adjust scrollTop by the difference.
  • Accessibility: screen readers only see rendered rows. Provide aria-rowcount, aria-rowindex, and keyboard navigation that scrolls to the target row. Search in page (Ctrl+F) does not find hidden rows.
  • Scroll anchoring, sticky headers, grids with columns, and horizontal windowing use the same range idea in two dimensions.
  • Libraries exist (react-window, TanStack Virtual), so in a real project, use one and explain the principle in the interview. The CSS property content-visibility: auto skips rendering work for off-screen content with no JavaScript, but the elements remain in the DOM.

Test the pure range function separately from the DOM code, because it holds the logic and edge cases: empty lists, lists shorter than the viewport, and scrolling past the end.

javascript
function visibleRange({ scrollTop, viewportHeight, rowHeight, count, overscan = 3 }) {
  if (count === 0) return { start: 0, end: 0 };
  const maxScroll = Math.max(0, count * rowHeight - viewportHeight);
  const top = Math.min(Math.max(0, scrollTop), maxScroll);
  const first = Math.floor(top / rowHeight);
  const last = Math.ceil((top + viewportHeight) / rowHeight);
  return {
    start: Math.max(0, first - overscan),
    end: Math.min(count, last + overscan),
  };
}

class VirtualList {
  constructor({ container, count, rowHeight, viewportHeight, renderRow, overscan = 3 }) {
    Object.assign(this, { container, count, rowHeight, viewportHeight, renderRow, overscan });
    this.range = { start: -1, end: -1 };
    this.renderCount = 0;
    this.top = document.createElement('div');
    this.body = document.createElement('div');
    this.bottom = document.createElement('div');
    container.append(this.top, this.body, this.bottom);
    container.setAttribute('role', 'list');
    container.setAttribute('aria-rowcount', String(count));
    this.update(0);
  }

  update(scrollTop) {
    const range = visibleRange({
      scrollTop,
      viewportHeight: this.viewportHeight,
      rowHeight: this.rowHeight,
      count: this.count,
      overscan: this.overscan,
    });
    if (range.start === this.range.start && range.end === this.range.end) return false;
    this.range = range;
    this.renderCount++;
    this.top.style.height = range.start * this.rowHeight + 'px';
    this.bottom.style.height = (this.count - range.end) * this.rowHeight + 'px';
    const fragment = document.createDocumentFragment();
    for (let i = range.start; i < range.end; i++) {
      const row = this.renderRow(i);
      row.style.height = this.rowHeight + 'px';
      row.setAttribute('aria-rowindex', String(i + 1));
      fragment.append(row);
    }
    this.body.replaceChildren(fragment);
    return true;
  }
}

const container = document.createElement('div');
document.body.append(container);
const list = new VirtualList({
  container,
  count: 50000,
  rowHeight: 30,
  viewportHeight: 300,
  renderRow: (i) => Object.assign(document.createElement('div'), { textContent: 'Row ' + i, role: 'listitem' }),
});

const summary = () => {
  const rows = list.body.children;
  const total = parseInt(list.top.style.height) + rows.length * 30 + parseInt(list.bottom.style.height);
  return `rows ${rows[0].textContent} to ${rows[rows.length - 1].textContent}, ${rows.length} nodes, total height ${total}`;
};

console.log('start:', summary());
console.log('scroll 1 px re-render:', list.update(1), '| scroll 25 px (same range):', list.update(25), '| 200 px:', list.update(200));
console.log('middle:', (list.update(600000), summary()));
console.log('end:', (list.update(10 ** 9), summary()));
console.log('render passes:', list.renderCount, '| DOM nodes in the page:', document.querySelectorAll('div').length);

console.log(visibleRange({ scrollTop: 0, viewportHeight: 100, rowHeight: 20, count: 0 }));
console.log(visibleRange({ scrollTop: 0, viewportHeight: 300, rowHeight: 20, count: 4 }));
console.log(visibleRange({ scrollTop: 50, viewportHeight: 100, rowHeight: 20, count: 100, overscan: 0 }));

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: start: rows Row 0 to Row 12, 13 nodes, total height 1500000 scroll 1 px re-render: true | scroll 25 px (same range): false | 200 px: true middle: rows Row 19997 to Row 20012, 16 nodes, total height 1500000 end: rows Row 49987 to Row 49999, 13 nodes, total height 1500000 render passes: 5 | DOM nodes in the page: 17 { start: 0, end: 0 } { start: 0, end: 4 } { start: 2, end: 8 }

Key points

  • Render only visible rows plus overscan inside a container with the full height.
  • start = floor(scrollTop / h), end = ceil((scrollTop + viewport) / h), clamped.
  • Use spacers or transforms so the scrollbar matches the full list.
  • Update only when the range changes, scheduled with requestAnimationFrame.
  • Variable heights need measurement, prefix sums, and binary search; accessibility needs aria row attributes.

Common mistakes

  • Rendering the whole list and hoping the browser handles it.
  • Omitting the overscan, which shows blank rows when scrolling fast.
  • Rebuilding the rows on every scroll event even when the range did not change.
  • Forgetting accessibility attributes and keyboard support for hidden rows.

Follow-ups

  • How would you support rows with different heights?
  • How would you keep the scroll position when items are added at the top?
  • When is content-visibility auto enough?

Tips

  • Give the formula and the clamp first, then the DOM structure.
  • Mention that Ctrl+F and screen readers only see rendered rows.
  • Say that in production you would use a tested library.