← Interview prep

JavaScript interview questions

Language fundamentals, ES features, and async behavior.

200 questions · Page 4 of 10

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

Page 4 of 10

Questions 61–80 of 200 · 0 of 20 on this page marked learned

61.javascript-0061Easyfresher

How do setTimeout and setInterval work, and what are their common gotchas?

setTimeout runs a function once after at least the given delay, and setInterval repeats it until cleared. The delay is a minimum, not a promise, because the callback waits for the stack to clear. Common bugs are calling the function instead of passing it, forgetting to clear intervals, losing this, and overlapping slow interval callbacks; a self-scheduling setTimeout is often safer.

Full answer

Both functions hand a callback to the timer system, return an identifier (a number in browsers, an object in Node.js), and let the event loop run the callback later. clearTimeout(id) and clearInterval(id) cancel it. Extra arguments after the delay are passed to the callback.

The delay is the earliest time the callback can run. It is placed in the macrotask queue when the time is up, but it still waits for the current code and any queued microtasks. A zero delay does not mean immediately, and browsers may raise very short delays for nested timers. Timers in background tabs can be slowed down further.

The classic mistake is writing setTimeout(doWork(), 1000). The parentheses call doWork right away, and the timer receives its return value. Browsers accept that silently and schedule nothing useful, while Node.js throws an error because the callback is not a function. Pass the function itself, setTimeout(doWork, 1000), or wrap it in an arrow function when arguments are needed.

setInterval has its own problems. It does not wait for the callback to finish, so a slow callback can run again right after the last one, and intervals drift when the main thread is busy. An interval that is never cleared keeps running and holds everything its callback references. A safer pattern is a function that schedules the next setTimeout after finishing its work, which guarantees a gap between runs.

Regular function callbacks lose this when passed to a timer. Use an arrow function or bind.

For animation, requestAnimationFrame is better than a short interval, since it matches the screen refresh.

javascript
const log = [];

setTimeout(() => log.push('timer 10 ms'), 10);
setTimeout(() => log.push('timer 0 ms'), 0);
log.push('sync');

function sayHello() {
  log.push('hello called right away');
  return undefined;
}
try {
  setTimeout(sayHello(), 1000); // bug: sayHello runs now and undefined is passed as the callback
} catch (error) {
  log.push('Node.js rejects the bad callback: ' + error.code);
}

setTimeout((name, mark) => log.push(`args: ${name} ${mark}`), 5, 'Asha', 90);

const cancelled = setTimeout(() => log.push('never runs'), 5);
clearTimeout(cancelled);

const counter = {
  count: 0,
  startBroken() {
    setTimeout(function () {
      log.push('regular function this.count: ' + this?.count);
    }, 1);
  },
  startFixed() {
    setTimeout(() => log.push('arrow function this.count: ' + this.count), 1);
  },
};
counter.startBroken();
counter.startFixed();

let ticks = 0;
const id = setInterval(() => {
  ticks += 1;
  log.push(`interval tick ${ticks}`);
  if (ticks === 3) clearInterval(id);
}, 15);

let step = 0;
function selfScheduling() {
  step += 1;
  log.push(`self-scheduled step ${step}`);
  if (step < 2) setTimeout(selfScheduling, 20);
}
setTimeout(selfScheduling, 100);

setTimeout(() => console.log(log.join('\n')), 300);

Run with Node.js v24.22.1 as js-61.js; two runs gave identical output. Output: sync hello called right away Node.js rejects the bad callback: ERR_INVALID_ARG_TYPE timer 0 ms regular function this.count: undefined arrow function this.count: 0 args: Asha 90 timer 10 ms interval tick 1 interval tick 2 interval tick 3 self-scheduled step 1 self-scheduled step 2

Key points

  • The delay is a minimum; the callback waits for the stack and microtasks.
  • Pass the function, not its call: setTimeout(fn, ms), not setTimeout(fn(), ms).
  • Always keep the id and clear intervals and timeouts when they are no longer needed.
  • setInterval can overlap or drift; a self-scheduling setTimeout keeps a gap.
  • Use requestAnimationFrame for animation.

Common mistakes

  • Passing the result of a call, setTimeout(fn(), ms), instead of the function.
  • Never clearing an interval that is created in a component or page that goes away.
  • Relying on exact timing; the delay is a minimum.
  • Using a regular function callback that expects this to be the surrounding object.

Follow-ups

  • Why can a setInterval callback run twice in quick succession?
  • What are the differences between setTimeout, setImmediate, and requestAnimationFrame?
  • How would you write a timer that does not drift over a long period?

Tips

  • Say "minimum delay" and explain the macrotask queue in one sentence.
  • Show the self-scheduling setTimeout pattern as the safer alternative to setInterval.
  • Mention clearing timers on teardown; it links to memory leaks.
62.javascript-0062Easyfresher

Which Object methods do you use to read, copy, and transform plain objects, and how does property order work?

Object.keys, values, and entries list own enumerable properties, Object.fromEntries builds an object back from pairs, Object.assign and spread copy properties, and Object.hasOwn checks ownership. Property order follows a fixed rule: integer-like keys ascending first, then string keys in creation order. Together these methods allow filtering and mapping objects the way arrays are handled.

Full answer

An object is a collection of key-value pairs. The static methods on Object read and reshape it.

Object.keys(obj), Object.values(obj), and Object.entries(obj) return arrays of the own, enumerable, string-keyed properties. Object.entries gives [key, value] pairs, which can be passed to array methods, and Object.fromEntries(pairs) turns pairs back into an object. This pair is the standard way to map or filter an object: convert to entries, use map or filter, convert back.

Object.assign(target, ...sources) copies properties into target and returns it, so it mutates the first argument. Spread, { ...a, ...b }, creates a new object instead, and later keys win. Both are shallow and read getters as plain values.

Object.hasOwn(obj, key) tells whether the key belongs to the object itself, and it replaced obj.hasOwnProperty(key), which can fail for objects without a prototype. The in operator also checks inherited keys. delete obj.key removes a property.

Property order is predictable. Keys that look like array indexes ('1', '42') come first in ascending numeric order, then other string keys in the order they were added, then symbols. This is why an object with keys 'b', '2', 'a', '1' lists 1, 2, b, a.

Shorthand properties ({ name }), computed keys ({ [key]: value }), and method shorthand keep object literals short. For dictionaries with arbitrary keys, a Map is often the better structure.

javascript
const marks = { maths: 90, physics: 72, chemistry: 35 };

console.log(Object.keys(marks), Object.values(marks));
console.log(Object.entries(marks));

const passed = Object.fromEntries(Object.entries(marks).filter(([, score]) => score >= 40));
console.log(passed);
const curved = Object.fromEntries(Object.entries(marks).map(([subject, score]) => [subject, score + 5]));
console.log(curved);

const total = Object.values(marks).reduce((sum, n) => sum + n, 0);
console.log(total);

const defaults = { theme: 'light', pageSize: 10 };
const target = { pageSize: 25 };
const result = Object.assign(target, defaults);
console.log(result === target, target);
console.log({ ...defaults, pageSize: 50 }, defaults);

const key = 'dynamic';
const name = 'Asha';
console.log({ name, [key + 'Key']: true, greet() { return 'hi'; } });

const mixed = { b: 1, 2: 'two', a: 2, 1: 'one', [Symbol('s')]: 'symbol' };
console.log(Object.keys(mixed), Reflect.ownKeys(mixed));

const inherited = Object.create({ fromPrototype: true });
inherited.own = true;
console.log('fromPrototype' in inherited, Object.hasOwn(inherited, 'fromPrototype'), Object.keys(inherited));

const bare = Object.create(null);
bare.x = 1;
console.log(Object.hasOwn(bare, 'x'), typeof bare.hasOwnProperty);

delete marks.chemistry;
console.log(marks, Object.entries(marks).length);

Run with Node.js v24.22.1 as js-62.js; two runs gave identical output. Output: [ 'maths', 'physics', 'chemistry' ] [ 90, 72, 35 ] [ [ 'maths', 90 ], [ 'physics', 72 ], [ 'chemistry', 35 ] ] { maths: 90, physics: 72 } { maths: 95, physics: 77, chemistry: 40 } 197 true { pageSize: 10, theme: 'light' } { theme: 'light', pageSize: 50 } { theme: 'light', pageSize: 10 } { name: 'Asha', dynamicKey: true, greet: [Function: greet] } [ '1', '2', 'b', 'a' ] [ '1', '2', 'b', 'a', Symbol(s) ] true false [ 'own' ] true undefined { maths: 90, physics: 72 } 2

Key points

  • keys, values, and entries list own enumerable string-keyed properties.
  • fromEntries is the inverse of entries; together they map and filter objects.
  • assign mutates its target; spread creates a new object; both are shallow.
  • hasOwn checks own keys; in also checks inherited keys.
  • Order: integer-like keys ascending, then string keys by creation, then symbols.

Common mistakes

  • Using Object.assign with a shared object as the first argument and mutating it by accident.
  • Assuming keys are listed in insertion order when some keys are integer-like.
  • Calling obj.hasOwnProperty on an object with a null prototype.
  • Expecting Object.keys to include inherited properties or symbols.

Follow-ups

  • What is the difference between Object.entries and Map entries?
  • How do you pick or omit certain keys from an object?
  • How would you merge two objects deeply?

Tips

  • Show the entries, map or filter, fromEntries round trip; it is the most useful idiom.
  • State the key-order rule with the integer-like example.
  • Prefer Object.hasOwn over hasOwnProperty in new code and say why.
63.javascript-0063Easyfresher

What is recursion, what are the base case and the recursive case, and what happens if the base case is missing?

Recursion is a function calling itself on a smaller version of the problem. It needs a base case that stops the calls and a recursive case that moves toward it. Each call adds a frame to the call stack, so a missing or unreachable base case ends in a RangeError for stack overflow. Some recursive solutions repeat work and are slow without memoization.

Full answer

A recursive function solves a problem by solving a smaller copy of the same problem. Two parts are required.

The base case is the simplest input, answered directly, and it stops the recursion. For factorial, factorial(0) is 1. The recursive case reduces the input and calls the function again, and uses the result: n * factorial(n - 1). Every chain of calls must move toward the base case.

Each call gets its own frame on the call stack, holding its parameters and local variables. The frames pile up until the base case returns, and then they unwind one by one as each result is combined. The stack has a limited size. A function that never reaches its base case, or a very deep input, throws RangeError: Maximum call stack size exceeded. The limit is typically around ten thousand frames, and it depends on the engine and on frame size.

Recursion fits problems that are naturally nested or self-similar: walking a folder tree, flattening nested arrays, parsing expressions, and divide-and-conquer algorithms. For simple counting loops, an iterative version uses constant stack space and is usually clearer.

Careless recursion can repeat work. The naive Fibonacci function calls itself twice, so it recomputes the same values thousands of times and takes exponential time. Remembering results (memoization) or looping removes the waste.

Engines in the JavaScript specification can optimize tail calls, but in practice only Safari implements this, so do not rely on it for deep recursion.

javascript
function factorial(n) {
  if (n <= 1) return 1; // base case
  return n * factorial(n - 1); // recursive case
}
console.log(factorial(5), factorial(0));

function sumNested(list) {
  let total = 0;
  for (const item of list) {
    total += Array.isArray(item) ? sumNested(item) : item;
  }
  return total;
}
console.log(sumNested([1, [2, [3, 4]], 5]));

function countdown(n) {
  if (n === 0) return 'done';
  return countdown(n - 1);
}
console.log(countdown(1000));

function withoutBaseCase(n) {
  return withoutBaseCase(n + 1);
}
try {
  withoutBaseCase(0);
} catch (error) {
  console.log(error.name, '-', error.message);
}

let calls = 0;
function fib(n) {
  calls += 1;
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
console.log(fib(20), 'calls:', calls);

const memo = new Map();
let memoCalls = 0;
function fastFib(n) {
  memoCalls += 1;
  if (n < 2) return n;
  if (memo.has(n)) return memo.get(n);
  const value = fastFib(n - 1) + fastFib(n - 2);
  memo.set(n, value);
  return value;
}
console.log(fastFib(20), 'calls:', memoCalls);

const folder = { name: 'root', children: [{ name: 'a', children: [{ name: 'a1', children: [] }] }, { name: 'b', children: [] }] };
const names = (node) => [node.name, ...node.children.flatMap(names)];
console.log(names(folder));

Run with Node.js v24.22.1 as js-63.js; two runs gave identical output. Output: 120 1 15 done RangeError - Maximum call stack size exceeded 6765 calls: 21891 6765 calls: 39 [ 'root', 'a', 'a1', 'b' ]

Key points

  • Every recursive function needs a base case and a recursive case that moves toward it.
  • Each call adds a stack frame; too many throws a RangeError.
  • Recursion suits nested or self-similar data such as trees.
  • Naive recursion can repeat work, as in Fibonacci; memoization fixes it.
  • Do not rely on tail call optimization in JavaScript.

Common mistakes

  • Forgetting the base case, or writing one the input can never reach.
  • Using naive recursive Fibonacci for large n.
  • Using recursion for a plain counting loop where iteration is simpler.
  • Assuming JavaScript removes tail calls automatically.

Follow-ups

  • How would you convert a recursive function into a loop with an explicit stack?
  • How deep can recursion go in your runtime, and what decides the limit?
  • What is the time complexity of naive and memoized Fibonacci?

Tips

  • State the two parts, base case and recursive case, before writing code.
  • Mention the stack and the RangeError; it shows you know what happens underneath.
  • Offer memoization when Fibonacci appears; interviewers expect it.
64.javascript-0064Easyfresher

What is the global object in JavaScript, and why does globalThis exist?

The global object holds the built-in global names and any global variables created with var in classic scripts or by accident. Its name differs by environment: window in a browser page, self in a worker, global in Node.js. globalThis is the standard name that works in all of them, so portable code uses it instead of guessing.

Full answer

Every JavaScript program runs with a global object. Built-in values such as Math, JSON, Promise, and parseInt are its properties, and in a browser it also carries document, fetch, and localStorage. The global scope is where top-level names live.

Different environments gave this object different names: window in a browser page, self in a Web Worker, global in Node.js. Code that had to run in more than one place needed awkward checks. globalThis was added in ES2020 and always points to the global object, so it works everywhere.

A few rules explain common surprises. In a classic browser script, a top-level var or function declaration becomes a property of window, while let, const, and class create global bindings that are not properties of it. In ES modules, top-level names are local to the module and attach to nothing. In a Node.js CommonJS file, top-level variables are local to the file, because Node wraps each file in a function. In sloppy mode, assigning to an undeclared name creates a property on the global object, which is why strict mode turns it into an error.

Environment detection should check for the feature, not the environment name. typeof window !== 'undefined' is a common test that is safe, since typeof does not throw for undeclared names. Adding custom properties to the global object is best avoided, because they can clash with other scripts.

javascript
console.log(typeof globalThis, globalThis === global, typeof window, typeof self);
console.log(typeof globalThis.Math, typeof globalThis.JSON, typeof globalThis.setTimeout);

var topLevelVar = 'file scoped in Node.js';
console.log(globalThis.topLevelVar, typeof topLevelVar);

globalThis.sharedFlag = 'set on the global object';
console.log(sharedFlag);
delete globalThis.sharedFlag;
console.log(typeof sharedFlag);

function leak() {
  leakedName = 'accidental global'; // no declaration, sloppy mode
}
leak();
console.log(globalThis.leakedName);
delete globalThis.leakedName;

function strictLeak() {
  'use strict';
  try {
    anotherLeak = 1;
  } catch (error) {
    return error.name;
  }
}
console.log(strictLeak());

function environment() {
  if (typeof window !== 'undefined' && typeof document !== 'undefined') return 'browser page';
  if (typeof process !== 'undefined' && process.versions?.node) return 'Node.js';
  return 'unknown';
}
console.log(environment());

console.log(Object.getOwnPropertyNames(globalThis).includes('Math'), 'console' in globalThis);

Run with Node.js v24.22.1 as js-64.js; two runs gave identical output. Output: object true undefined undefined object object function undefined string set on the global object undefined accidental global ReferenceError Node.js true true

Key points

  • The global object holds built-ins and global variables.
  • Its name differs: window, self, or global; globalThis works everywhere.
  • Classic scripts attach top-level var to window; let, const, and modules do not.
  • Node.js files and ES modules have their own local scope.
  • Sloppy mode creates globals from undeclared assignments; strict mode throws.

Common mistakes

  • Assuming window exists everywhere; it does not exist in Node.js or workers.
  • Creating accidental globals by forgetting let or const.
  • Expecting top-level let or const in a browser script to appear on window.
  • Using typeof window as the only environment check for code that also runs in modern runtimes that define it.

Follow-ups

  • Why does typeof not throw for an undeclared variable?
  • How does the scope of top-level declarations differ between a classic script and a module?
  • How would you provide a polyfill that attaches to the global object safely?

Tips

  • Name globalThis and say it was added to unify window, self, and global.
  • Explain the var versus let difference on the global object.
  • Mention accidental globals and strict mode to connect the answer to common bugs.
65.javascript-0065Easyfresher

How do you select and update elements in the DOM, and what is the difference between textContent and innerHTML?

querySelector and querySelectorAll select elements by CSS selector, while getElementById is the fast lookup by id. textContent sets plain text and is safe, whereas innerHTML parses a string as HTML and is dangerous with untrusted input. createElement with append builds nodes without parsing, and classList, dataset, and setAttribute update classes, data values, and attributes.

Full answer

The Document Object Model (DOM) is the live tree of objects the browser builds from HTML. JavaScript reads and changes the page by changing that tree.

To select: document.querySelector(selector) returns the first match or null, querySelectorAll returns a static NodeList of every match, and getElementById finds one element by id. getElementsByClassName returns a live HTMLCollection that updates when the page changes, which can surprise a loop. A NodeList from querySelectorAll supports forEach, and spread turns it into a real array.

To update, there are several properties. textContent sets or reads plain text, and any markup in the string is shown as text. innerHTML parses the string as HTML, so it can build structure quickly, but placing untrusted text in it allows cross-site scripting. innerText depends on rendering and is slower. For structure without parsing, document.createElement, then set properties, then append to a parent. element.remove() deletes an element.

Classes change with classList.add, remove, toggle, and contains. Data attributes read through dataset: data-user-id becomes dataset.userId. Other attributes use getAttribute, setAttribute, and removeAttribute. Form values use the value property.

Reading the DOM and writing to it repeatedly can be slow. Building a DocumentFragment or a single string and inserting once reduces repaints. If the selector finds nothing, querySelector returns null, so check before using the result.

javascript
document.body.innerHTML = `
  <ul id="courses">
    <li class="course" data-level="easy">HTML</li>
    <li class="course" data-level="hard">JavaScript</li>
  </ul>
  <p id="note"></p>`;

const list = document.querySelector('#courses');
const first = document.querySelector('.course');
const all = document.querySelectorAll('.course');
console.log(first.textContent, all.length, document.querySelector('.missing'));
console.log([...all].map((li) => li.dataset.level));

const live = document.getElementsByClassName('course');
const staticList = document.querySelectorAll('.course');
const extra = document.createElement('li');
extra.className = 'course';
extra.textContent = 'CSS';
list.append(extra);
console.log('live collection:', live.length, 'static list:', staticList.length);

extra.classList.add('highlight');
extra.classList.toggle('highlight');
extra.classList.toggle('done', true);
extra.dataset.level = 'medium';
extra.setAttribute('title', 'Styling');
console.log(extra.outerHTML);

const note = document.getElementById('note');
const userInput = '<img src=x onerror="alert(1)">';
note.textContent = userInput;
console.log(note.innerHTML);
console.log('children created from textContent:', note.children.length);
note.innerHTML = userInput;
console.log('children created from innerHTML:', note.children.length);

const fragment = document.createDocumentFragment();
for (const name of ['React', 'Node']) {
  const li = document.createElement('li');
  li.textContent = name;
  fragment.append(li);
}
list.append(fragment);
console.log([...list.children].map((li) => li.textContent));

first.remove();
console.log(list.children.length);

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: HTML 2 null [ 'easy', 'hard' ] live collection: 3 static list: 2 <li class="course done" data-level="medium" title="Styling">CSS</li> &lt;img src=x onerror="alert(1)"&gt; children created from textContent: 0 children created from innerHTML: 1 [ 'HTML', 'JavaScript', 'CSS', 'React', 'Node' ] 4

Key points

  • querySelector gives the first match or null; querySelectorAll gives a static NodeList.
  • getElementsByClassName gives a live HTMLCollection.
  • textContent treats text as text; innerHTML parses HTML and is unsafe with untrusted input.
  • createElement plus append builds nodes without parsing.
  • classList, dataset, and setAttribute update classes, data, and attributes.

Common mistakes

  • Using innerHTML with user-provided text.
  • Using the result of querySelector without checking for null.
  • Looping over a live HTMLCollection while adding or removing elements in the loop.
  • Reading and writing layout properties alternately in a loop, which forces repeated layout.

Follow-ups

  • What is the difference between a NodeList and an HTMLCollection?
  • When would you use insertAdjacentHTML or the Sanitizer API?
  • How does event delegation reduce the need to select every element?

Tips

  • Contrast textContent and innerHTML in terms of security first; that is the usual follow-up.
  • Mention live versus static collections; most candidates do not.
  • Use createElement and append for dynamic content and explain why it is safer.
66.javascript-0066Easyfresher

What is an array-like object, and how is it different from an iterable and a real array?

An array-like object has a length and indexed items but is not an Array, so it lacks methods such as map and filter. An iterable has a Symbol.iterator method and works with for...of and spread. Array.from converts either kind into a real array and accepts a mapping function, which also makes it a tool for generating sequences.

Full answer

Three related ideas are easy to confuse.

A real array is created by [], Array.of, or Array.from. Array.isArray returns true for it, and it has all array methods. An array-like object has numeric keys starting at 0 and a length property, for example the arguments object, a DOM NodeList, an HTMLCollection, or the plain object { 0: 'a', 1: 'b', length: 2 }. It can be read with a for loop and an index, but calling map on it fails because the method does not exist.

An iterable is anything with a [Symbol.iterator]() method: arrays, strings, Sets, Maps, generators, and many DOM lists. for...of, spread, and destructuring work with iterables. An object can be array-like, iterable, both, or neither. A string is both. The plain object above is array-like but not iterable, so [...obj] throws a TypeError, while a Set is iterable but has no length or indexes.

Array.from(source, mapFn) accepts either kind and returns a new real array. Its second argument maps each item as the array is built. A useful trick is Array.from({ length: 5 }, (_, i) => i * 2), which creates a sequence without holes. By contrast, new Array(5) creates a sparse array with empty slots that map skips, and fill can set them.

Array methods can also be borrowed with Array.prototype.map.call(arrayLike, fn), though Array.from is the modern choice.

javascript
function showArguments() {
  return [Array.isArray(arguments), arguments.length, typeof arguments.map];
}
console.log(showArguments(1, 2, 3));

const arrayLike = { 0: 'a', 1: 'b', length: 2 };
console.log(Array.from(arrayLike), Array.prototype.map.call(arrayLike, (x) => x + x));
try {
  console.log([...arrayLike]);
} catch (error) {
  console.log('spread of array-like:', error.name);
}

const set = new Set(['x', 'y']);
console.log(typeof set.length, [...set], Array.from(set, (v) => v.toUpperCase()));
console.log(Array.from('héllo'), Array.from(new Map([['k', 1]])));

console.log(Array.from({ length: 5 }, (_, i) => i * 2));
console.log(Array.from({ length: 3 }, () => 'row'));

const sparse = new Array(3);
console.log(sparse, sparse.map(() => 1), 0 in sparse);
console.log(new Array(3).fill(0), [...new Array(3)].map((_, i) => i));

const grid = Array.from({ length: 2 }, () => Array(2).fill('.'));
grid[0][0] = '#';
console.log(grid);
const brokenGrid = new Array(2).fill(Array(2).fill('.'));
brokenGrid[0][0] = '#';
console.log(brokenGrid);

console.log(Array.of(3), Array(3).length, Array.isArray(Array.from(arrayLike)));

Run with Node.js v24.22.1 as js-66.js; two runs gave identical output. Output: [ false, 3, 'undefined' ] [ 'a', 'b' ] [ 'aa', 'bb' ] spread of array-like: TypeError undefined [ 'x', 'y' ] [ 'X', 'Y' ] [ 'h', 'é', 'l', 'l', 'o' ] [ [ 'k', 1 ] ] [ 0, 2, 4, 6, 8 ] [ 'row', 'row', 'row' ] [ <3 empty items> ] [ <3 empty items> ] false [ 0, 0, 0 ] [ 0, 1, 2 ] [ [ '#', '.' ], [ '.', '.' ] ] [ [ '#', '.' ], [ '#', '.' ] ] [ 3 ] 3 true

Key points

  • Array-like: numeric indexes plus length, but no array methods.
  • Iterable: has Symbol.iterator and works with for...of and spread.
  • An object can be one, both, or neither; a string is both.
  • Array.from converts either kind and takes an optional map function.
  • new Array(n) creates empty slots; Array.from({ length: n }, fn) creates real items.

Common mistakes

  • Calling map or filter directly on a NodeList or arguments object.
  • Using new Array(n).map(...) and getting skipped empty slots.
  • Filling a two-dimensional grid with one shared inner array through fill.
  • Spreading an array-like object that is not iterable.

Follow-ups

  • Which DOM collections are iterable and which are only array-like?
  • What does Array(3) differ from Array.of(3)?
  • How do typed arrays relate to normal arrays?

Tips

  • Define the three terms in one sentence each, then show the object that is array-like but not iterable.
  • Mention the Array.from({ length }) idiom; it is useful in many coding questions.
  • Point out the fill trap with nested arrays.
67.javascript-0067Easyfresher

How do Math.round, floor, ceil, and trunc differ, and how do you generate a random integer in a range?

floor rounds down, ceil rounds up, trunc removes the fraction, and round goes to the nearest integer with halves rounding up toward positive infinity. They differ for negative numbers. A random integer from min to max inclusive is Math.floor(Math.random() * (max - min + 1)) + min. Math.random is not secure and cannot be seeded, so tests and security code need other tools.

Full answer

The four rounding functions only agree for positive numbers.

  • Math.floor(x) returns the largest integer not greater than x, so -2.5 becomes -3.
  • Math.ceil(x) returns the smallest integer not less than x, so -2.5 becomes -2.
  • Math.trunc(x) drops the fractional part, moving toward zero, so -2.5 becomes -2.
  • Math.round(x) goes to the nearest integer and rounds a tie (.5) toward positive infinity, so 2.5 becomes 3 and -2.5 becomes -2.

Math.random() returns a float from 0 up to but not including 1. To get an integer from min to max, both included, scale it by the size of the range, floor it, and shift it: Math.floor(Math.random() * (max - min + 1)) + min. Using Math.round here would make the end values half as likely as the others.

To shuffle an array fairly, use the Fisher-Yates algorithm: walk from the end, swap each item with a random earlier or equal position. Sorting with a random comparator is biased and slow.

Math.random cannot be seeded, so tests that depend on it are not repeatable. For tests, inject a small seeded generator. For passwords, tokens, or anything security-related, use crypto.getRandomValues or crypto.randomUUID, since Math.random is predictable.

Other useful facts: Math.max() with no arguments is -Infinity, Math.max(...[]) too, and any NaN argument makes the result NaN.

javascript
for (const x of [2.5, -2.5, 2.4, -2.6]) {
  console.log(String(x).padStart(5), Math.floor(x), Math.ceil(x), Math.trunc(x), Math.round(x));
}

function randomInt(min, max, random = Math.random) {
  return Math.floor(random() * (max - min + 1)) + min;
}

let allInRange = true;
const seen = new Set();
for (let i = 0; i < 10000; i++) {
  const value = randomInt(1, 6);
  seen.add(value);
  if (value < 1 || value > 6 || !Number.isInteger(value)) allInRange = false;
}
console.log('all in range:', allInRange, 'sides seen:', [...seen].sort());

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;
  };
}
const seeded = mulberry32(42);
console.log(Array.from({ length: 5 }, () => randomInt(1, 100, seeded)));

function shuffle(list, random = Math.random) {
  const copy = [...list];
  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;
}
console.log(shuffle([1, 2, 3, 4, 5], mulberry32(7)));

console.log(Math.max(), Math.min(), Math.max(1, NaN), Math.max(...[3, 9, 4]));
console.log(typeof crypto.randomUUID(), crypto.getRandomValues(new Uint8Array(4)).length);

Run with Node.js v24.22.1 as js-67.js; two runs gave identical output. Output: 2.5 2 3 2 3 -2.5 -3 -2 -2 -2 2.4 2 3 2 2 -2.6 -3 -2 -2 -3 all in range: true sides seen: [ 1, 2, 3, 4, 5, 6 ] [ 61, 45, 86, 67, 18 ] [ 4, 2, 3, 5, 1 ] -Infinity Infinity NaN 9 string 4

Key points

  • floor goes down, ceil up, trunc toward zero, round to nearest with ties toward +Infinity.
  • They differ for negative numbers.
  • Random integer in [min, max]: floor(random * (max - min + 1)) + min.
  • Fisher-Yates gives an unbiased shuffle; sort with a random comparator does not.
  • Math.random is not seedable and not secure; use crypto for security.

Common mistakes

  • Using Math.round to scale a random number and making the end values less likely.
  • Using Math.floor on negative numbers when truncation toward zero was intended.
  • Sorting with a random comparator to shuffle.
  • Using Math.random for tokens, passwords, or other security-related values.

Follow-ups

  • Why does arr.sort(() => Math.random() - 0.5) give a biased result?
  • How would you pick a random item from an array?
  • How would you pick items with different weights?

Tips

  • Lay out the negative-number cases in a small table; that is where answers usually go wrong.
  • Write the range formula and say why it uses floor and plus one.
  • Mention the security limit of Math.random and name crypto.getRandomValues.
68.javascript-0068Easyfresher

How does short-circuit evaluation work, and what are the logical assignment operators ||=, &&=, and ??=?

The operators &&, ||, and ?? evaluate the right side only when the left side does not already decide the result, and they return one of their operands. The logical assignment operators ||=, &&=, and ??= assign only under the matching condition: when the left is falsy, truthy, or nullish. They are shorter than writing the if statement and also skip the assignment when it is not needed.

Full answer

Short-circuit evaluation means the engine stops as soon as the result is known. For a && b, if a is falsy the answer is a and b is never evaluated. For a || b, if a is truthy the answer is a. For a ?? b, if a is anything except null and undefined, the answer is a. The skipped side may be a function call, so side effects do not happen. This makes patterns like isReady && start() or cache[key] || compute(key) possible, although an if statement is usually clearer for side effects.

The three logical assignment operators combine this with assignment:

  • a ||= b means a || (a = b). It assigns only if a is falsy.
  • a &&= b means a && (a = b). It assigns only if a is truthy.
  • a ??= b means a ?? (a = b). It assigns only if a is null or undefined.

??= is the most useful. It sets a default without overwriting 0, false, or an empty string, for example options.retries ??= 3. ||= replaces any falsy value, which is rarely wanted for numbers. &&= updates a value only if it exists.

Unlike a = a || b, the logical forms do not perform the assignment when the condition fails. This matters for setters and for frozen or read-only properties, because no write is attempted. The ternary condition ? x : y is the choice when both outcomes are values, and it should not be nested deeply.

javascript
const calls = [];
const tracked = (label, value) => {
  calls.push(label);
  return value;
};

console.log(tracked('left', 0) && tracked('right', 'x'), calls);
calls.length = 0;
console.log(tracked('left', 'a') || tracked('right', 'b'), calls);
calls.length = 0;
console.log(tracked('left', null) ?? tracked('right', 'fallback'), calls);

const options = { retries: 0, label: '', timeout: undefined, verbose: true };
options.retries ||= 3;
options.label ||= 'untitled';
options.timeout ??= 5000;
options.verbose &&= 'yes';
options.missing &&= 'never set';
console.log(options);

const settings = { retries: 0, name: '' };
settings.retries ??= 3;
settings.name ??= 'guest';
console.log(settings);

const locked = Object.freeze({ mode: 'dark' });
locked.mode ||= 'light'; // condition is truthy, so no write is attempted
console.log(locked.mode);
try {
  (function () {
    'use strict';
    locked.mode = locked.mode || 'light'; // always writes, so strict mode throws
  })();
} catch (error) {
  console.log('plain assignment on frozen object:', error.name);
}

const score = 72;
const grade = score >= 90 ? 'A' : score >= 60 ? 'B' : 'C';
console.log(grade);

Run with Node.js v24.22.1 as js-68.js; two runs gave identical output. Output: 0 [ 'left' ] a [ 'left' ] fallback [ 'left', 'right' ] { retries: 3, label: 'untitled', timeout: 5000, verbose: 'yes' } { retries: 0, name: '' } dark plain assignment on frozen object: TypeError B

Key points

  • Short-circuit operators skip the right side when the left side decides the result.
  • They return an operand, not necessarily a boolean.
  • ||= assigns on falsy, &&= on truthy, ??= on null or undefined.
  • ??= is the safe way to set defaults for values like 0 and false.
  • The logical forms skip the write when the condition fails.

Common mistakes

  • Using ||= for numeric defaults and replacing a valid 0.
  • Relying on short-circuit expressions for important side effects instead of an if statement.
  • Nesting ternary operators until the result is hard to read.
  • Assuming a ||= b always writes; it only writes when a is falsy.

Follow-ups

  • What does a ||= b do for a getter and setter pair?
  • How do short-circuit operators interact with optional chaining?
  • Why is a && b || c not the same as a ternary?

Tips

  • Give the long form for each operator, such as a ?? (a = b); it proves you know what they do.
  • Recommend ??= for defaults and explain the zero example.
  • Keep side effects in if statements and say so.
69.javascript-0069Easyfresher

How do default parameters work in JavaScript, and when are the default values evaluated?

A default parameter value is used when the argument is missing or undefined, and it is evaluated freshly on every call. A default can use earlier parameters, call functions, and be an object or array that is new each time. null, 0, and false do not trigger a default. Defaults also change how function.length and the parameter scope behave.

Full answer

Writing function greet(name = 'guest') gives the parameter a value when the caller passes nothing or passes undefined. Other values count as given, including null, 0, false, and ''. If null should also trigger a default, handle it with ?? inside the function.

The default expression is evaluated at call time, every time it is needed, and only if the argument is missing. This has three consequences. A default such as [] or {} creates a new object on every call, so calls do not share state, unlike in some other languages. A default may be a function call, such as createdAt = Date.now(), and it runs only when used. A default may use parameters that come before it: function area(width, height = width). Using a later parameter, or the parameter itself, hits the temporal dead zone and throws a ReferenceError.

Default parameters live in their own scope between the function's outer scope and its body, so a closure in a default sees the parameters, not variables declared in the body.

A function's length property counts only the parameters before the first one with a default, which matters for helpers such as curry. The arguments object is not linked to defaulted parameters.

Destructured parameters can also have defaults, at both levels: function connect({ host = 'localhost', port = 80 } = {}). The outer = {} lets the function be called with no argument at all.

Required parameters can be enforced with a default that throws, for example value = required('value').

javascript
function greet(name = 'guest') {
  return `Hello, ${name}`;
}
console.log(greet(), greet(undefined), greet(null), greet(''));

function addItem(item, list = []) {
  list.push(item);
  return list;
}
console.log(addItem('a'), addItem('b')); // a new list for each call

function area(width, height = width) {
  return width * height;
}
console.log(area(4), area(4, 5));

try {
  (function (a = b, b = 1) {})();
} catch (error) {
  console.log('later parameter:', error.name);
}

let evaluations = 0;
const makeId = () => `id-${++evaluations}`;
function createUser(name, id = makeId()) {
  return { name, id };
}
console.log(createUser('Asha'), createUser('Ravi', 'custom'), createUser('Meera'));
console.log('default evaluated', evaluations, 'times');

function connect({ host = 'localhost', port = 80 } = {}) {
  return `${host}:${port}`;
}
console.log(connect(), connect({ port: 8080 }), connect({ host: 'example.com' }));

console.log(((a, b = 2, c) => {}).length, ((a, b) => {}).length);

function required(name) {
  throw new TypeError(`${name} is required`);
}
function save(id = required('id')) {
  return id;
}
try {
  save();
} catch (error) {
  console.log(error.message);
}

function nullOrMissing(value) {
  value ??= 'default';
  return value;
}
console.log(nullOrMissing(null), nullOrMissing(0));

Run with Node.js v24.22.1 as js-69.js; two runs gave identical output. Output: Hello, guest Hello, guest Hello, null Hello, [ 'a' ] [ 'b' ] 16 20 later parameter: ReferenceError { name: 'Asha', id: 'id-1' } { name: 'Ravi', id: 'custom' } { name: 'Meera', id: 'id-2' } default evaluated 2 times localhost:80 localhost:8080 example.com:80 1 2 id is required default 0

Key points

  • Defaults apply for a missing or undefined argument only.
  • They are evaluated on each call, so an object default is fresh every time.
  • A default can use earlier parameters but not later ones.
  • function.length counts only parameters before the first default.
  • Destructured parameters need an outer = {} to allow a call with no arguments.

Common mistakes

  • Expecting null to trigger the default value.
  • Assuming a default object is shared between calls.
  • Referencing a later parameter in a default and getting a ReferenceError.
  • Forgetting the outer = {} for a destructured parameter and crashing when no argument is passed.

Follow-ups

  • How does function.length change when defaults are used, and why does that matter for currying?
  • What is the scope of a closure created inside a default expression?
  • How would you validate required arguments in a function?

Tips

  • Say "evaluated on each call" and give the fresh-array example; it is the main insight.
  • Mention that null does not trigger defaults, and show ?? as the fix.
  • Include the destructured-parameter pattern with = {}; it is common in real code.
70.javascript-0070Mediummid

How can tagged templates be used to build safe, readable helpers such as parameterized queries and dedented text?

A tag function receives the fixed text pieces and the interpolated values separately, so it can treat values as data and never splice them into the text. This makes parameterized SQL builders, escaping helpers, and dedent utilities possible with plain template syntax. The pieces array is frozen, has a raw version, and is the same object for each evaluation of one call site.

Full answer

A tagged template calls a function with strings (an array of the literal pieces) followed by each interpolated value as separate arguments. The function decides what to do with them and can return any value, not only text.

The safest use is a query builder. Instead of joining user input into the SQL string, the tag places a placeholder such as $1 where each value was, and returns the text and the values separately. The database driver then sends them apart, so input is never parsed as SQL. The code reads like a normal template, yet injection is not possible through the interpolated values. The same approach works for escaping HTML, as in the earlier example, and for building shell arguments.

Another use is formatting. A dedent tag removes the shared indentation from a multi-line template, which keeps embedded text tidy in indented code. String.raw and strings.raw provide the unprocessed source text, useful for regular expressions and file paths.

Properties worth knowing: strings is frozen, and strings.raw is a parallel array. For one call site in the source, the engine passes the same strings object every time, which lets a library cache work done on the template. For a${1}b, strings has one more entry than the values.

A tag can also compose nested results. A sql tag can accept another sql fragment as a value and merge its text and values, so conditions can be assembled safely.

Tags do not make unsafe output safe automatically. The author of the tag defines the behavior.

javascript
function sql(strings, ...values) {
  let text = '';
  const params = [];
  strings.forEach((piece, i) => {
    text += piece;
    if (i >= values.length) return;
    const value = values[i];
    if (value && value.isSql) {
      text += value.text.replace(/\$(\d+)/g, (_, n) => `$${Number(n) + params.length}`);
      params.push(...value.params);
    } else {
      params.push(value);
      text += `$${params.length}`;
    }
  });
  return { text, params, isSql: true };
}

const name = "Robert'); DROP TABLE students;--";
const minMarks = 40;
const query = sql`SELECT * FROM students WHERE name = ${name} AND marks >= ${minMarks}`;
console.log(query.text);
console.log(query.params);

const onlyActive = sql`active = ${true}`;
const combined = sql`SELECT id FROM users WHERE city = ${'Pune'} AND ${onlyActive}`;
console.log(combined.text, combined.params);

function dedent(strings, ...values) {
  const full = strings.reduce((out, piece, i) => out + piece + (i < values.length ? values[i] : ''), '');
  const lines = full.replace(/^\n/, '').split('\n');
  const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => l.match(/^ */)[0].length));
  return lines.map((l) => l.slice(indent)).join('\n').trimEnd();
}
const message = dedent`
    Dear ${'Asha'},
      your marks are ${88}.
    Regards`;
console.log(message);

function inspect(strings) {
  return { frozen: Object.isFrozen(strings), raw: strings.raw[0], cooked: strings[0] };
}
console.log(inspect`line\none`);

const sites = [];
function remember(strings) {
  sites.push(strings);
}
for (let i = 0; i < 2; i++) remember`same call site ${i}`;
remember`same call site ${0}`;
console.log(sites[0] === sites[1], sites[0] === sites[2]);

Run with Node.js v24.22.1 as js-70.js; two runs gave identical output. Output: SELECT * FROM students WHERE name = $1 AND marks >= $2 [ "Robert'); DROP TABLE students;--", 40 ] SELECT id FROM users WHERE city = $1 AND active = $2 [ 'Pune', true ] Dear Asha, your marks are 88. Regards { frozen: true, raw: 'line\\none', cooked: 'line\none' } true false

Key points

  • A tag receives literal pieces and values separately and may return anything.
  • A sql tag turns values into placeholders, preventing injection through interpolated values.
  • dedent and String.raw are formatting uses.
  • strings is frozen and is the same object for each evaluation of one call site.
  • Nested fragments need the tag to merge their text and values.

Common mistakes

  • Concatenating values into the SQL text inside the tag, which brings back injection.
  • Assuming a tagged template is automatically safe; the tag decides.
  • Forgetting that strings has one more element than the values.
  • Using cooked strings where the raw source text is needed, such as regex or path sources.

Follow-ups

  • How would a tag return a function or an object rather than a string?
  • Why does the engine give the same strings object for each evaluation of a call site?
  • How would you write an html tag that escapes values but accepts trusted nested html fragments?

Tips

  • Use the parameterized query as the headline example; it is the one with real security value.
  • Mention that strings is frozen and cached per call site for libraries that cache.
  • Say that the tag author is responsible for safety.
71.javascript-0071Mediummid

How does the iteration protocol work in detail, including early exit with return(), and what are iterator helpers?

An iterable returns a fresh iterator from [Symbol.iterator](), and the iterator's next() gives { value, done }. When a loop exits early with break, return, or a throw, the language calls the iterator's optional return() method so it can clean up. Iterator helpers such as map, filter, take, and toArray build lazy pipelines directly on iterators in current runtimes.

Full answer

The protocol has two layers. An iterable has a [Symbol.iterator]() method that returns an iterator. An iterator has a next() method that returns { value, done }. Many built-in iterators are also iterable and return themselves, so they can be used in for...of but only once. An array, by contrast, returns a new iterator each time, so it can be looped repeatedly.

Consumers such as for...of, spread, destructuring, Array.from, Map, and Promise.all call next() until done is true. Destructuring stops after the items it needs.

Cleanup is the part many candidates miss. If a consumer stops before done becomes true, because of break, return, a thrown error, or destructuring fewer items, it calls the iterator's optional return() method. A generator turns this into running its finally blocks. A custom iterator can release a file handle, a database cursor, or a lock in return(). When the loop finishes normally, return() is not called.

Iterators can be lazy. A chain of generators, or the iterator helper methods map, filter, take, drop, flatMap, toArray, and reduce on Iterator.prototype, processes one item at a time through the whole pipeline. With take(3) on an infinite source, only three items are ever pulled. These helpers are available in Node.js 22 and current browsers; check support for older targets.

Errors in the iterator or the consumer follow the same cleanup rule, so always release resources in return() or finally.

javascript
class Resource {
  constructor(items) {
    this.items = items;
  }
  [Symbol.iterator]() {
    let index = 0;
    const items = this.items;
    console.log('open');
    return {
      next: () => (index < items.length ? { value: items[index++], done: false } : { value: undefined, done: true }),
      return: () => {
        console.log('close (return called)');
        return { done: true };
      },
    };
  }
}

for (const item of new Resource(['a', 'b', 'c'])) {
  console.log('item', item);
  if (item === 'b') break;
}
console.log('--- full loop');
for (const item of new Resource(['x'])) console.log('item', item);
console.log('--- destructuring');
const [firstOnly] = new Resource([1, 2, 3]);
console.log(firstOnly);

function* withCleanup() {
  try {
    yield 1;
    yield 2;
  } finally {
    console.log('generator finally ran');
  }
}
for (const n of withCleanup()) {
  console.log('generator value', n);
  break;
}

const once = [10, 20][Symbol.iterator]();
console.log([...once], [...once]);
const list = [10, 20];
console.log([...list], [...list]);

function* naturals() {
  let n = 1;
  while (true) yield n++;
}
const pipeline = naturals()
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .take(4);
console.log(pipeline.toArray());
console.log(naturals().drop(2).take(3).reduce((sum, n) => sum + n, 0));

Run with Node.js v24.22.1 as js-71.js; two runs gave identical output. Output: open item a item b close (return called) --- full loop open item x --- destructuring open close (return called) 1 generator value 1 generator finally ran [ 10, 20 ] [] [ 10, 20 ] [ 10, 20 ] [ 4, 16, 36, 64 ] 12

Key points

  • Iterable returns an iterator; the iterator's next() returns { value, done }.
  • Iterators from built-ins are one-shot; arrays give a fresh iterator each time.
  • Early exit (break, return, throw, partial destructuring) calls return() for cleanup.
  • Generators run finally blocks when return() is called.
  • Iterator helpers (map, filter, take, toArray) build lazy pipelines on iterators.

Common mistakes

  • Assuming return() runs when a loop finishes normally; it runs only on early exit.
  • Reusing a consumed iterator and getting an empty result the second time.
  • Opening a resource in [Symbol.iterator]() and never releasing it on early exit.
  • Using iterator helpers in an environment that does not support them yet.

Follow-ups

  • What does a generator do when return() is called while it is paused outside a try block?
  • How do async iterators and for await...of handle early exit?
  • How would you write a lazy take(n) helper without the built-in?

Tips

  • Mention the return() cleanup rule; it is the detail that shows depth.
  • Contrast an iterable (reusable) with a one-shot iterator.
  • Show a lazy pipeline over an infinite source to prove why laziness matters.
72.javascript-0072Mediummid

How do you avoid stack overflow in deep recursion, and what happens with tail call optimization in JavaScript?

Each recursive call uses a stack frame, so very deep recursion throws a RangeError. A tail call is a call in return position, and the language specification allows reusing the frame, but only Safari implements it, so JavaScript code cannot rely on it. Practical fixes are a loop, an explicit stack, or a trampoline that returns thunks instead of calling itself.

Full answer

The call stack has a fixed size. A recursive function that goes tens of thousands of levels deep, such as summing a long linked list, throws RangeError: Maximum call stack size exceeded, even though the logic is correct. The exact depth depends on the engine and on how much each frame stores.

A tail call is a function call that is the last thing a function does, as in return sum(n - 1, total + n). Because nothing is left to do after the call returns, an engine could replace the current frame with the new one and use constant stack space. ES2015 standardized this proper tail call behavior. In practice, only Safari (JavaScriptCore) implements it. V8 and SpiderMonkey chose not to, partly for debugging reasons, so portable code must not depend on it.

Reliable alternatives:

  • Rewrite as a loop. This is the simplest fix for linear recursion such as sums and counters.
  • Use an explicit stack (an array) for tree and graph traversals. The function keeps its own list of work, so depth is limited by memory, not by the call stack.
  • Use a trampoline. The recursive function returns a function (a thunk) describing the next step instead of calling itself. A small loop keeps running thunks until a real value appears. Stack depth stays constant at the cost of some allocation.
  • Reduce the depth with a better algorithm, such as divide and conquer.

Mutual recursion and deep recursion on user-controlled input are also a risk: a crafted deeply nested input can crash a parser, so bound the depth.

javascript
function sumRecursive(n) {
  return n === 0 ? 0 : n + sumRecursive(n - 1);
}
try {
  console.log(sumRecursive(1000));
  console.log(sumRecursive(200000));
} catch (error) {
  console.log('deep recursion:', error.name);
}

function sumTail(n, total = 0) {
  return n === 0 ? total : sumTail(n - 1, total + n); // a tail call, not optimized in Node.js
}
try {
  console.log(sumTail(200000));
} catch (error) {
  console.log('tail call without optimization:', error.name);
}

function trampoline(fn) {
  return (...args) => {
    let result = fn(...args);
    while (typeof result === 'function') result = result();
    return result;
  };
}
const sumTrampolined = trampoline(function step(n, total = 0) {
  return n === 0 ? total : () => step(n - 1, total + n);
});
console.log(sumTrampolined(200000));

const sumLoop = (n) => {
  let total = 0;
  for (let i = 1; i <= n; i++) total += i;
  return total;
};
console.log(sumLoop(200000));

function buildNested(depth) {
  let node = { value: 0, children: [] };
  const root = node;
  for (let i = 1; i < depth; i++) {
    const child = { value: i, children: [] };
    node.children.push(child);
    node = child;
  }
  return root;
}
function maxDepthRecursive(node) {
  return 1 + Math.max(0, ...node.children.map(maxDepthRecursive));
}
function maxDepthIterative(root) {
  let deepest = 0;
  const stack = [[root, 1]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    deepest = Math.max(deepest, depth);
    for (const child of node.children) stack.push([child, depth + 1]);
  }
  return deepest;
}
const tree = buildNested(50000);
try {
  maxDepthRecursive(tree);
} catch (error) {
  console.log('recursive traversal:', error.name);
}
console.log('explicit stack:', maxDepthIterative(tree));

Run with Node.js v24.22.1 as js-72.js; two runs gave identical output. Output: 500500 deep recursion: RangeError tail call without optimization: RangeError 20000100000 20000100000 recursive traversal: RangeError explicit stack: 50000

Key points

  • Deep recursion throws RangeError because the call stack is limited.
  • A tail call is the last action of a function; the spec allows frame reuse, but only Safari implements it.
  • Loops and explicit stacks are the reliable fixes.
  • A trampoline returns thunks and a loop runs them, keeping the stack flat.
  • Limit recursion depth on untrusted nested input.

Common mistakes

  • Relying on tail call optimization in code that runs in Node.js or Chrome.
  • Using recursion for traversing very deep or user-supplied structures without a depth limit.
  • Using a trampoline for a function that returns a function as its real result, which the loop would keep calling.
  • Raising the stack size with engine flags instead of fixing the algorithm.

Follow-ups

  • How would you convert a recursive depth-first search into an iterative one?
  • Why did some engines decline to implement proper tail calls?
  • How does JSON.parse handle very deeply nested input?

Tips

  • State clearly that tail calls are standardized but not portable.
  • Offer the three fixes in order: loop, explicit stack, trampoline.
  • Mention untrusted nested input as a real-world cause.
73.javascript-0073Mediummid

How do you update objects and arrays immutably in JavaScript, and why does it matter for change detection?

Immutable updates build new objects and arrays instead of changing existing ones, using spread, map, filter, and the non-mutating methods toSorted, toReversed, toSpliced, and with. Parts that did not change keep their references, so a cheap Object.is check on identity can tell whether anything changed. UI libraries rely on this for fast change detection.

Full answer

A mutation changes a value in place, such as list.push(1) or user.age = 30. An immutable update leaves the old value untouched and returns a new one. This keeps history intact, avoids bugs where two parts of a program share and silently change the same data, and makes change detection cheap: if the reference is the same, nothing changed.

For objects, spread copies the top level and then overrides keys: { ...user, age: 30 }. For nested data, copy every level on the path to the change and reuse the rest: { ...state, user: { ...state.user, address: { ...state.user.address, city: 'Delhi' } } }. The parts off that path keep their original references, which is called structural sharing.

For arrays, add with [...list, item], remove with filter, change one item with map, and use the ES2023 methods that return copies: toSorted, toReversed, toSpliced, and with(index, value). Compare these with sort, reverse, splice, and push, which mutate.

Change detection then reduces to Object.is(oldValue, newValue). React's state, memoization, and dependency checks and Redux-style stores depend on this. If code mutates and reuses the reference, the check says "unchanged" and the screen does not update.

Spread is shallow, so updating deep structures by hand becomes long. Helper libraries or the structuredClone function can help, but a full deep clone loses structural sharing and costs more. Object.freeze in development can catch accidental mutations, though it is shallow.

javascript
const state = {
  user: { name: 'Asha', address: { city: 'Pune', pin: '411001' } },
  courses: ['HTML', 'CSS', 'JS'],
  settings: { theme: 'light' },
};

const next = {
  ...state,
  user: { ...state.user, address: { ...state.user.address, city: 'Delhi' } },
};
console.log(state.user.address.city, next.user.address.city);
console.log('changed branch:', next.user !== state.user, next.user.address !== state.user.address);
console.log('shared branches:', next.settings === state.settings, next.courses === state.courses);

const list = [3, 1, 2];
console.log(list.toSorted(), list.toReversed(), list.with(0, 99), list.toSpliced(1, 1), list);
const withItem = [...list, 4];
const without = list.filter((n) => n !== 1);
const replaced = list.map((n) => (n === 2 ? 20 : n));
console.log(withItem, without, replaced, list);

const mutated = state.courses;
mutated.push('React');
console.log(Object.is(mutated, state.courses), 'same reference: a change check would miss it');

function updateIfChanged(old, key, value) {
  return Object.is(old[key], value) ? old : { ...old, [key]: value };
}
const unchanged = updateIfChanged(state.settings, 'theme', 'light');
const changed = updateIfChanged(state.settings, 'theme', 'dark');
console.log(unchanged === state.settings, changed === state.settings, changed);

const frozen = Object.freeze({ count: 1, nested: { value: 1 } });
try {
  (function () {
    'use strict';
    frozen.count = 2;
  })();
} catch (error) {
  console.log('mutation caught:', error.name);
}
frozen.nested.value = 2; // freeze is shallow
console.log(frozen.nested.value);

const replacedCourses = state.courses.map((c) => (c === 'CSS' ? 'Sass' : c));
console.log(replacedCourses, state.courses);

Run with Node.js v24.22.1 as js-73.js; two runs gave identical output. Output: Pune Delhi changed branch: true true shared branches: true true [ 1, 2, 3 ] [ 2, 1, 3 ] [ 99, 1, 2 ] [ 3, 2 ] [ 3, 1, 2 ] [ 3, 1, 2, 4 ] [ 3, 2 ] [ 3, 1, 20 ] [ 3, 1, 2 ] true same reference: a change check would miss it true false { theme: 'dark' } mutation caught: TypeError 2 [ 'HTML', 'Sass', 'JS', 'React' ] [ 'HTML', 'CSS', 'JS', 'React' ]

Key points

  • Immutable updates return new values and leave the old ones unchanged.
  • Copy each level along the path to the change; share the rest.
  • Use map, filter, spread, toSorted, toReversed, toSpliced, and with for arrays.
  • Identity checks with Object.is make change detection cheap.
  • Spread and freeze are shallow; a full deep clone loses sharing.

Common mistakes

  • Believing spread makes a deep copy and mutating nested objects of the copy.
  • Mutating state and keeping the same reference, so change checks see no change.
  • Deep cloning the whole state for each update and losing structural sharing.
  • Using sort or reverse on shared arrays, which change the original.

Follow-ups

  • How does a library like Immer let you write mutating code and still produce immutable results?
  • What is the cost of copying a large array on every update, and how do persistent data structures help?
  • How does React decide whether to re-render when state is an object?

Tips

  • Explain why it matters in one sentence: identity checks are fast and safe.
  • Show the nested update path and point out which branches are shared.
  • List the non-mutating array methods from ES2023.
74.javascript-0074Mediummid

What is the structured clone algorithm, which values can it copy, and what does transferring an ArrayBuffer do?

The structured clone algorithm is the built-in way to deep copy values. structuredClone and postMessage both use it. It handles many types that JSON cannot, such as Date, Map, Set, typed arrays, and cycles, but it fails for functions and DOM nodes and drops prototypes. Transferring an ArrayBuffer moves its memory to the new owner without copying and leaves the original empty.

Full answer

Structured cloning is how browsers copy data between realms: into a Web Worker with postMessage, into IndexedDB, and through structuredClone(value) in your own code. The algorithm walks the value, copies it, and remembers objects it has seen so that cycles and shared references stay intact.

It supports primitives (except symbols), Boolean, String, and Number wrapper objects, Date, RegExp, Map, Set, ArrayBuffer and typed arrays, BigInt, Error objects (with their name and message), arrays, and plain objects. It does not support functions (a DataCloneError), DOM nodes, and symbols as values. For class instances, only own enumerable data properties are copied and the prototype is lost, so methods disappear. Getters are called and their results are copied as plain values. Property descriptors and non-enumerable properties are not preserved.

Cloned data is fully separate from the original. A Map keyed by objects keeps the relationship between its cloned keys, and two references to the same object in the input still point to one cloned object in the output.

Transferring is an option for big binary data. When an ArrayBuffer is listed in the transfer option, its memory moves to the new owner, no bytes are copied, and the original buffer becomes detached with a byteLength of 0. It is the fast way to hand a large image or audio buffer to a worker. A SharedArrayBuffer is not transferred but shared, which is a different feature.

Because a clone is a snapshot, later changes on either side are not visible to the other.

javascript
const original = {
  created: new Date('2026-04-01T00:00:00Z'),
  pattern: /ab+c/gi,
  tags: new Set(['js']),
  scores: new Map([[{ id: 1 }, 90]]),
  big: 12345678901234567890n,
  bytes: new Uint8Array([1, 2, 3]),
};
original.self = original;

const copy = structuredClone(original);
console.log(copy.created instanceof Date, copy.pattern.flags, copy.tags.has('js'), copy.big);
console.log(copy.self === copy, copy.self !== original, copy.bytes !== original.bytes);

const shared = { value: 1 };
const twoRefs = structuredClone({ a: shared, b: shared });
console.log(twoRefs.a === twoRefs.b);

class Student {
  constructor(name) {
    this.name = name;
  }
  get upper() {
    return this.name.toUpperCase();
  }
  hello() {
    return 'hi';
  }
}
const student = structuredClone(new Student('Asha'));
console.log(student instanceof Student, typeof student.hello, student.name);

const withGetter = structuredClone({ get computed() { return 42; } });
console.log(Object.getOwnPropertyDescriptor(withGetter, 'computed'));

for (const [label, value] of [['function', { fn() {} }], ['symbol', Symbol('s')]]) {
  try {
    structuredClone(value);
  } catch (error) {
    console.log(label, '->', error.name);
  }
}
console.log(structuredClone(new Error('failed')).message);

const buffer = new ArrayBuffer(8);
const moved = structuredClone(buffer, { transfer: [buffer] });
console.log('original:', buffer.byteLength, buffer.detached, 'moved:', moved.byteLength);

const { port1, port2 } = new MessageChannel();
const data = new Uint8Array(4).buffer;
port2.onmessage = (event) => {
  console.log('received', event.data.byteLength, 'sender sees', data.byteLength);
  port1.close();
};
port1.postMessage(data, [data]);

Run with Node.js v24.22.1 as js-74.js; two runs gave identical output. Output: true gi true 12345678901234567890n true true true true false undefined Asha { value: 42, writable: true, enumerable: true, configurable: true } function -> DataCloneError symbol -> DataCloneError failed original: 0 true moved: 8 received 4 sender sees 0

Key points

  • structuredClone and postMessage use the same algorithm.
  • Supports Date, RegExp, Map, Set, typed arrays, BigInt, Error, and cycles; not functions or DOM nodes.
  • Class instances lose their prototype; getters become plain values.
  • Shared references and cycles are preserved in the copy.
  • Transfer moves an ArrayBuffer without copying and detaches the original.

Common mistakes

  • Expecting class instances to keep their methods after cloning.
  • Passing functions or DOM nodes and getting a DataCloneError.
  • Using a transferred buffer after the transfer and finding it empty.
  • Assuming cloning keeps getters as getters.

Follow-ups

  • How is a SharedArrayBuffer different from a transferred ArrayBuffer?
  • Which types does JSON handle that structuredClone does not, and the reverse?
  • How would you copy a class instance and keep its prototype?

Tips

  • Name the supported types that JSON lacks: Date, Map, Set, cycles, and typed arrays.
  • State the prototype loss for class instances; it is the common surprise.
  • Explain transfer as a move with no copy, and mention that the sender loses access.
75.javascript-0075Mediummid

How do you format numbers, dates, plurals, and lists for different locales with the Intl API?

The Intl object gives built-in, locale-aware formatting: NumberFormat for numbers and currencies, DateTimeFormat for dates with an explicit time zone, PluralRules for singular and plural categories, RelativeTimeFormat for phrases like "2 days ago", and ListFormat for lists. These replace hand-written string code and hard-coded separators, which break for other locales.

Full answer

People write numbers, dates, and lists differently around the world. One thousand two hundred and thirty-four and a half is 1,234.5 in the US, 1.234,5 in Germany, and 1,234.5 in India with grouping of 12,34,567 for larger values. Building these strings by hand is error-prone, so JavaScript has Intl.

Intl.NumberFormat(locale, options) formats plain numbers, currencies (style: 'currency', currency: 'INR'), percentages, units, and compact forms like 1.2K. The currency code is separate from the locale, since a German reader may view prices in Indian rupees.

Intl.DateTimeFormat formats dates. Always pass timeZone, otherwise the server or user machine zone is used. Use dateStyle and timeStyle for common patterns, or detailed options for exact parts.

Intl.PluralRules returns a category such as one, other, few, or many for a number. English has two forms, but Polish or Arabic have more, so code like count === 1 ? 'item' : 'items' is wrong in many languages. Plural categories map to translated strings.

Intl.RelativeTimeFormat produces "in 3 days" or "yesterday" (with numeric: 'auto'). Intl.ListFormat joins items as "A, B, and C" with the right conjunction and punctuation. Intl.Collator sorts text correctly, Intl.DisplayNames gives names for languages and regions, and Intl.Segmenter splits text by grapheme or word.

Creating a formatter is more costly than using one, so create it once and reuse it in loops. Output can differ slightly between engines and versions, so tests should not compare exact strings from different environments.

javascript
const amount = 1234567.891;
console.log(new Intl.NumberFormat('en-US').format(amount));
console.log(new Intl.NumberFormat('de-DE').format(amount));
console.log(new Intl.NumberFormat('en-IN').format(amount));

const rupees = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 });
console.log(rupees.format(1499.5));
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(1499.5));
console.log(new Intl.NumberFormat('en', { notation: 'compact' }).format(1250000));
console.log(new Intl.NumberFormat('en', { style: 'percent' }).format(0.256));
console.log(new Intl.NumberFormat('en', { style: 'unit', unit: 'kilometer-per-hour' }).format(60));

const moment = new Date('2026-08-15T09:05:00Z');
const parts = { timeZone: 'Asia/Kolkata', dateStyle: 'long', timeStyle: 'short', hourCycle: 'h23' };
console.log(new Intl.DateTimeFormat('en-GB', parts).format(moment));
console.log(new Intl.DateTimeFormat('en-US', { timeZone: 'UTC', year: 'numeric', month: 'long', day: 'numeric' }).format(moment));
console.log(new Intl.DateTimeFormat('de-DE', { timeZone: 'UTC', weekday: 'long', month: 'long', day: 'numeric' }).format(moment));

const english = new Intl.PluralRules('en');
const polish = new Intl.PluralRules('pl');
console.log([0, 1, 2].map((n) => english.select(n)), [1, 2, 5, 22].map((n) => polish.select(n)));
const ordinals = new Intl.PluralRules('en', { type: 'ordinal' });
const suffix = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
console.log([1, 2, 3, 4, 11, 21].map((n) => n + suffix[ordinals.select(n)]).join(' '));

const relative = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(relative.format(-1, 'day'), '|', relative.format(3, 'week'), '|', relative.format(0, 'day'));

const list = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log(list.format(['HTML', 'CSS', 'JavaScript']), '|', new Intl.ListFormat('en', { type: 'disjunction' }).format(['a', 'b']));
console.log(new Intl.DisplayNames('en', { type: 'region' }).of('IN'), new Intl.DisplayNames('en', { type: 'language' }).of('hi'));

Run with Node.js v24.22.1 as js-75.js; two runs gave identical output. Output: 1,234,567.891 1.234.567,891 12,34,567.891 ₹1,500 $1,499.50 1.3M 26% 60 km/h 15 August 2026 at 14:35 August 15, 2026 Samstag, 15. August [ 'other', 'one', 'other' ] [ 'one', 'few', 'many', 'few' ] 1st 2nd 3rd 4th 11th 21st yesterday | in 3 weeks | today HTML, CSS, and JavaScript | a or b India Hindi

Key points

  • Use Intl instead of hand-written separators and plural rules.
  • NumberFormat handles currency, percent, unit, and compact styles; currency is independent of locale.
  • Always set an explicit timeZone in DateTimeFormat.
  • PluralRules gives categories because many languages have more than two forms.
  • Reuse formatter objects; avoid exact-string tests across environments.

Common mistakes

  • Hard-coding thousands separators, currency symbols, or count === 1 plural logic.
  • Formatting dates without a timeZone and getting different output on each machine.
  • Creating a new formatter object for every item in a long list.
  • Comparing formatted strings in tests that run in different environments.

Follow-ups

  • How would you build a message like "3 files" or "1 file" for many languages?
  • What is the difference between a locale and a currency in NumberFormat?
  • How does Intl.Collator handle accents and numbers in sorting?

Tips

  • Show PluralRules with a language that has more than two forms; it proves the point quickly.
  • Say "explicit timeZone" every time dates come up.
  • Mention reuse of formatter objects as a performance point.
76.javascript-0076Mediummid

How does the fetch API handle errors, and how do you send JSON, read responses safely, and set a timeout?

fetch rejects only for network failures, not for HTTP error statuses, so code must check response.ok. The body can be read once with json() or text(), and a bad body throws a separate error. JSON requests need a Content-Type header and a stringified body, and AbortSignal.timeout adds a time limit that rejects with a TimeoutError.

Full answer

fetch(url, options) returns a promise for a Response. The promise rejects when no response arrives, for example when the network is down, DNS fails, or the request is aborted. A response with status 404 or 500 is still a successful fetch from the promise's point of view. Code must check response.ok (true for statuses 200 to 299) or response.status, and throw its own error otherwise.

The body is a stream that can be read once: response.json(), response.text(), response.blob(), or response.arrayBuffer(). Calling two of them on the same response fails, since bodyUsed becomes true. Use response.clone() before reading when two reads are needed. json() can throw if the body is not valid JSON, so an error response with an HTML body needs care.

To send JSON, set method: 'POST', add the header Content-Type: application/json, and pass body: JSON.stringify(data). Without the header, many servers do not parse the body. Cookies are not sent to other origins by default; the credentials option controls that.

For timeouts and cancellation, pass signal. AbortSignal.timeout(ms) gives a signal that aborts itself and rejects with a TimeoutError. Combine it with a user cancel signal using AbortSignal.any.

A small wrapper that checks ok, parses JSON, and adds status information to errors keeps application code short. Retrying should be limited to safe, repeatable requests.

The code below starts a local test server, so it runs without internet access. In a browser, the same fetch calls work against a real URL, subject to CORS.

javascript
const http = require('node:http');

const server = http.createServer((req, res) => {
  if (req.url === '/ok') {
    res.setHeader('Content-Type', 'application/json');
    return res.end(JSON.stringify({ message: 'hello' }));
  }
  if (req.url === '/missing') {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/html');
    return res.end('<h1>Not found</h1>');
  }
  if (req.url === '/echo' && req.method === 'POST') {
    let body = '';
    req.on('data', (chunk) => (body += chunk));
    return req.on('end', () => {
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({ received: JSON.parse(body), type: req.headers['content-type'] }));
    });
  }
  if (req.url === '/slow') return setTimeout(() => res.end('late'), 300);
  res.statusCode = 500;
  res.end('unexpected');
});

async function getJson(url, options) {
  const response = await fetch(url, options);
  if (!response.ok) {
    const error = new Error(`HTTP ${response.status}`);
    error.status = response.status;
    throw error;
  }
  return response.json();
}

server.listen(0, '127.0.0.1', async () => {
  const base = `http://127.0.0.1:${server.address().port}`;

  console.log(await getJson(`${base}/ok`));

  const notFound = await fetch(`${base}/missing`);
  console.log('404 did not reject:', notFound.ok, notFound.status);
  try {
    await notFound.json();
  } catch (error) {
    console.log('HTML body parsed as JSON:', error.name);
  }
  try {
    await getJson(`${base}/missing`);
  } catch (error) {
    console.log('wrapper error:', error.message, error.status);
  }

  console.log(await getJson(`${base}/echo`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Asha' }),
  }));

  const once = await fetch(`${base}/ok`);
  const copy = once.clone();
  await once.json();
  console.log('bodyUsed:', once.bodyUsed, 'clone still readable:', (await copy.json()).message);
  try {
    await once.json();
  } catch (error) {
    console.log('second read:', error.name);
  }

  try {
    await fetch(`${base}/slow`, { signal: AbortSignal.timeout(50) });
  } catch (error) {
    console.log('timeout:', error.name);
  }

  const closed = http.createServer().listen(0, '127.0.0.1');
  await new Promise((resolve) => closed.once('listening', resolve));
  const closedPort = closed.address().port;
  await new Promise((resolve) => closed.close(resolve));
  try {
    await fetch(`http://127.0.0.1:${closedPort}/`);
  } catch (error) {
    console.log('network failure:', error.name);
  }

  server.close();
  server.closeAllConnections();
});

Run with Node.js v24.22.1 as js-76.js; two runs gave identical output. Output: { message: 'hello' } 404 did not reject: false 404 HTML body parsed as JSON: SyntaxError wrapper error: HTTP 404 404 { received: { name: 'Asha' }, type: 'application/json' } bodyUsed: true clone still readable: hello second read: TypeError timeout: TimeoutError network failure: TypeError

Key points

  • fetch rejects on network failure or abort, not on 404 or 500.
  • Check response.ok and throw for error statuses.
  • The body can be read once; use clone() for two reads.
  • JSON requests need a Content-Type header and a stringified body.
  • AbortSignal.timeout adds a timeout; the rejection is a TimeoutError.

Common mistakes

  • Assuming fetch rejects on 404 or 500 and skipping the response.ok check.
  • Forgetting the Content-Type header when sending JSON.
  • Reading the body twice without cloning.
  • Having no timeout, so a stalled request waits indefinitely.

Follow-ups

  • How would you upload a file or form data with fetch?
  • How do credentials: 'include' and cookies interact with CORS?
  • How would you retry only safe requests?

Tips

  • Lead with "fetch only rejects on network failure"; it is the question's main trap.
  • Show a small wrapper that checks ok and throws a typed error.
  • Mention AbortSignal.timeout for timeouts; it replaces manual timer code.
77.javascript-0077Hardsenior

What are web streams, how does backpressure work, and how would you parse a streamed response incrementally?

A ReadableStream delivers data in chunks that a consumer pulls through a reader or a pipe, and a TransformStream changes chunks in the middle. Backpressure lets a slow consumer slow the producer, so memory stays bounded. When parsing a stream, chunk boundaries do not match record boundaries, so the parser must buffer the partial last line between chunks.

Full answer

Streams let a program process data as it arrives instead of waiting for all of it. A ReadableStream is a source of chunks, a WritableStream is a destination, and a TransformStream is a pair that turns input chunks into output chunks. response.body from fetch is a ReadableStream of Uint8Array chunks, so text can start to be processed before the download ends. Large files, logs, and live feeds fit streaming well, and memory use depends on the chunk size, not on the total size.

stream.getReader() gives a reader whose read() returns { value, done }. pipeThrough(transform) and pipeTo(writable) connect streams and handle errors and closing. TextDecoderStream turns bytes into text, taking care of multi-byte characters split across chunks.

Backpressure is the flow-control rule. Each stream has a queue with a high water mark. When the queue is full, desiredSize drops to zero or below, and the producer should pause until the consumer reads. In pull-based sources, the pull() callback is only called when there is room, so a fast producer cannot flood a slow consumer. Piping applies this automatically.

The classic parsing pitfall is that a chunk is an arbitrary slice of bytes. A line, a JSON record, or even a character can be cut in the middle. A correct parser keeps a buffer: append the decoded chunk, split on the newline, emit all complete lines, and keep the last incomplete piece for the next chunk. After the stream ends, it must flush the remaining buffer.

Streams are single-consumer. Use tee() to create two branches, and cancel the reader when the consumer stops early so the producer can release resources.

javascript
const http = require('node:http');

const server = http.createServer((req, res) => {
  const chunks = ['{"id":1}\n{"id"', ':2}\n{"i', 'd":3}\n{"id":4}'];
  let index = 0;
  const timer = setInterval(() => {
    if (index < chunks.length) res.write(chunks[index++]);
    else {
      clearInterval(timer);
      res.end(); // no trailing newline: the last record needs the flush step
    }
  }, 10);
});

function splitLines() {
  let buffer = '';
  return new TransformStream({
    transform(text, controller) {
      buffer += text;
      const lines = buffer.split('\n');
      buffer = lines.pop(); // keep the incomplete tail
      for (const line of lines) if (line) controller.enqueue(line);
    },
    flush(controller) {
      if (buffer) controller.enqueue(buffer);
    },
  });
}

server.listen(0, '127.0.0.1', async () => {
  const response = await fetch(`http://127.0.0.1:${server.address().port}/`);
  const rawChunks = [];
  const records = response.body
    .pipeThrough(new TransformStream({
      transform(chunk, controller) {
        rawChunks.push(chunk.length);
        controller.enqueue(chunk);
      },
    }))
    .pipeThrough(new TextDecoderStream())
    .pipeThrough(splitLines());

  const reader = records.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    console.log('record:', JSON.parse(value));
  }
  console.log('network chunks were received:', rawChunks.length > 0);

  const log = [];
  let produced = 0;
  const source = new ReadableStream({
    pull(controller) {
      produced += 1;
      log.push(`pull ${produced}`);
      controller.enqueue(produced);
      if (produced === 6) controller.close();
    },
  }, { highWaterMark: 2 });
  const sourceReader = source.getReader();
  await new Promise((resolve) => setTimeout(resolve, 20));
  console.log('before any read, pulls already made:', log.length, '(highWaterMark is 2)');
  const first = await sourceReader.read();
  await new Promise((resolve) => setTimeout(resolve, 20));
  console.log('after one read:', first.value, 'pulls so far:', log.length);

  const encoded = new TextEncoder().encode('héllo');
  const half = [encoded.slice(0, 2), encoded.slice(2)];
  const naive = half.map((bytes) => new TextDecoder().decode(bytes)).join('');
  const streaming = new TextDecoder();
  const careful = streaming.decode(half[0], { stream: true }) + streaming.decode(half[1]);
  console.log(JSON.stringify(naive), careful);

  server.close();
  server.closeAllConnections();
});

Run with Node.js v24.22.1 as js-77.js; two runs gave identical output. Output: record: { id: 1 } record: { id: 2 } record: { id: 3 } record: { id: 4 } network chunks were received: true before any read, pulls already made: 2 (highWaterMark is 2) after one read: 1 pulls so far: 3 "h��llo" héllo

Key points

  • Streams process data chunk by chunk, so memory does not grow with total size.
  • response.body is a ReadableStream of bytes; pipeThrough and pipeTo connect stages.
  • Backpressure: a full queue pauses the producer until the consumer reads.
  • Chunks do not align with records; buffer the incomplete tail and flush at the end.
  • Use TextDecoderStream for correct multi-byte decoding and cancel early to release resources.

Common mistakes

  • Assuming each chunk contains complete lines or records.
  • Forgetting to flush the leftover buffer when the stream ends.
  • Decoding bytes with a fresh TextDecoder for each chunk, which breaks multi-byte characters.
  • Reading the whole body into memory with response.text() when the data is large.

Follow-ups

  • How does tee() affect memory when one branch reads more slowly than the other?
  • How would you cancel a download when the consumer no longer needs the data?
  • How do Node.js streams differ from web streams?

Tips

  • Describe backpressure as "a full queue tells the producer to wait"; then name highWaterMark.
  • Show the tail buffer for line parsing; it is the standard real-world bug.
  • Mention TextDecoderStream for multi-byte safety.
78.javascript-0078Mediummid

What is CORS, why does it exist, and how do preflight requests work?

The same-origin policy stops a page from reading responses from another origin, and CORS is the way a server opts in to share them by sending Access-Control headers. Browsers enforce it; the server still receives the request. Requests that are not simple trigger a preflight OPTIONS request, and credentials require a specific allowed origin instead of a wildcard.

Full answer

An origin is the combination of scheme, host, and port. By default, a script from https://app.example may send requests to https://api.example, but the browser will not let it read the response. This same-origin policy protects users: otherwise any website could read your logged-in email or bank pages through your browser.

Cross-origin resource sharing (CORS) is a controlled exception. The server tells the browser which origins may read its responses by adding headers such as Access-Control-Allow-Origin: https://app.example. The browser compares this with the page's origin and either exposes the response or blocks it. Two facts clear up many misunderstandings. CORS is enforced by browsers only, so tools like curl and server code are not affected. And a blocked response does not mean the server ignored the request: a simple request, such as a form-style POST, may still have changed data on the server.

Simple requests (a few methods and headers, such as GET and a basic Content-Type) go straight out. Other requests, for example a PUT, or a POST with Content-Type: application/json, or a custom header, cause a preflight. The browser first sends an OPTIONS request with Origin, Access-Control-Request-Method, and Access-Control-Request-Headers. The server answers with Access-Control-Allow-Methods, Access-Control-Allow-Headers, and optionally Access-Control-Max-Age to cache the answer. Only then does the browser send the real request.

For cookies or HTTP authentication, the client sets credentials: 'include', and the server must reply with Access-Control-Allow-Credentials: true and a specific origin, because * is not allowed with credentials. When the allowed origin varies, add Vary: Origin so caches keep separate copies.

Common fixes are server-side headers or a same-origin proxy. Disabling CORS in the browser is not a fix for users.

javascript
const http = require('node:http');

const allowedOrigins = new Set(['https://app.example']);

const server = http.createServer((req, res) => {
  const origin = req.headers.origin;
  if (origin && allowedOrigins.has(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Vary', 'Origin');
  }
  if (req.method === 'OPTIONS') {
    if (origin && allowedOrigins.has(origin)) {
      res.setHeader('Access-Control-Allow-Methods', 'GET, PUT');
      res.setHeader('Access-Control-Allow-Headers', req.headers['access-control-request-headers'] || '');
      res.setHeader('Access-Control-Max-Age', '600');
    }
    res.statusCode = 204;
    return res.end();
  }
  res.setHeader('Content-Type', 'application/json');
  res.end(JSON.stringify({ secret: 'data' }));
});

function send(port, method, headers) {
  return new Promise((resolve) => {
    http.request({ host: '127.0.0.1', port, method, path: '/', headers }, (res) => {
      res.resume();
      res.on('end', () => {
        const picked = Object.fromEntries(
          Object.entries(res.headers).filter(([name]) => name.startsWith('access-control') || name === 'vary')
        );
        resolve({ status: res.statusCode, ...picked });
      });
    }).end();
  });
}

server.listen(0, '127.0.0.1', async () => {
  const port = server.address().port;
  console.log('allowed origin GET:', await send(port, 'GET', { Origin: 'https://app.example' }));
  console.log('other origin GET:  ', await send(port, 'GET', { Origin: 'https://evil.example' }));
  console.log('no origin GET:     ', await send(port, 'GET', {}));
  console.log('preflight:         ', await send(port, 'OPTIONS', {
    Origin: 'https://app.example',
    'Access-Control-Request-Method': 'PUT',
    'Access-Control-Request-Headers': 'content-type',
  }));
  server.close();
});

Run with Node.js v24.22.1 as js-78.js; two runs gave identical output. Output: allowed origin GET: { status: 200, 'access-control-allow-origin': 'https://app.example', 'access-control-allow-credentials': 'true', vary: 'Origin' } other origin GET: { status: 200 } no origin GET: { status: 200 } preflight: { status: 204, 'access-control-allow-origin': 'https://app.example', 'access-control-allow-credentials': 'true', vary: 'Origin', 'access-control-allow-methods': 'GET, PUT', 'access-control-allow-headers': 'content-type', 'access-control-max-age': '600' }

Key points

  • Origin is scheme, host, and port; same-origin policy blocks reading cross-origin responses.
  • CORS is the server's opt-in via Access-Control headers; only browsers enforce it.
  • Non-simple requests trigger an OPTIONS preflight before the real request.
  • Credentials require a specific origin and Allow-Credentials: true; not the wildcard.
  • Add Vary: Origin when the allowed origin changes per request.

Common mistakes

  • Believing CORS protects the server. It protects users by limiting which pages can read responses.
  • Using Access-Control-Allow-Origin: * together with credentials.
  • Reflecting any Origin header back without checking an allow list.
  • Fixing a CORS error by changing frontend code when the server headers are missing.

Follow-ups

  • Which requests count as simple, and which trigger a preflight?
  • Why does CORS not protect against CSRF?
  • What does Access-Control-Expose-Headers do?

Tips

  • Start from the same-origin policy and explain CORS as an opt-in; the story is then easy to follow.
  • Say that the server still receives the request; many candidates miss it.
  • Describe the preflight in two sentences with the three request headers.
79.javascript-0079Mediummid

How do cookies work, and what do the HttpOnly, Secure, SameSite, Domain, Path, and expiry attributes do?

A cookie is a small name-value pair the server sets with a Set-Cookie header and the browser sends back with matching requests. HttpOnly hides it from JavaScript, Secure limits it to HTTPS, SameSite controls cross-site sending, Domain and Path decide which requests include it, and Max-Age or Expires set its lifetime. Session cookies for logins should use HttpOnly, Secure, and SameSite.

Full answer

HTTP is stateless, so cookies carry state between requests, most often a session identifier. The server sends Set-Cookie: sid=abc123; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600. The browser stores it and adds Cookie: sid=abc123 to later requests that match the cookie's rules. Each cookie is limited to roughly 4 KB.

The attributes control behavior:

  • Max-Age (seconds) or Expires (a date) sets the lifetime. Without both, it is a session cookie that ends when the browser session ends. Setting Max-Age=0 deletes it.
  • Domain and Path define scope. Without Domain, the cookie goes only to the exact host that set it. Setting a parent domain shares it with subdomains.
  • Secure sends the cookie only over HTTPS.
  • HttpOnly makes it invisible to document.cookie, which limits what an injected script can steal.
  • SameSite=Strict sends the cookie only for same-site requests, Lax also sends it for top-level navigations such as clicking a link, and None (which requires Secure) sends it in all contexts. Browsers treat a missing value as Lax. This reduces cross-site request forgery.
  • The __Host- name prefix forces Secure, Path=/, and no Domain, which is the strictest scope.

document.cookie reads all non-HttpOnly cookies as one string, and assigning to it sets or updates one cookie at a time, which is awkward. The newer Cookie Store API is a cleaner interface in supporting browsers.

Cookies are sent on every matching request, including images, so large cookies slow pages down. For data that the server does not need, localStorage avoids that cost. Authentication tokens in cookies should use HttpOnly and Secure, and state-changing endpoints still need CSRF protection.

javascript
const http = require('node:http');

const server = http.createServer((req, res) => {
  res.setHeader('Set-Cookie', [
    'sid=abc123; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600',
    'theme=dark; Path=/; Max-Age=31536000',
    '__Host-token=t1; Secure; Path=/; SameSite=Strict',
  ]);
  res.end(`you sent: ${req.headers.cookie ?? 'no cookie'}`);
});

function parseSetCookie(header) {
  const [pair, ...attributes] = header.split(';').map((part) => part.trim());
  const [name, ...rest] = pair.split('=');
  const result = { name, value: rest.join('='), httpOnly: false, secure: false };
  for (const attribute of attributes) {
    const [key, value = ''] = attribute.split('=');
    const lower = key.toLowerCase();
    if (lower === 'httponly') result.httpOnly = true;
    else if (lower === 'secure') result.secure = true;
    else if (lower === 'samesite') result.sameSite = value;
    else if (lower === 'max-age') result.maxAgeSeconds = Number(value);
    else if (lower === 'path') result.path = value;
  }
  return result;
}

function visibleToScript(cookies) {
  return cookies.filter((cookie) => !cookie.httpOnly).map((cookie) => `${cookie.name}=${cookie.value}`).join('; ');
}

server.listen(0, '127.0.0.1', async () => {
  const response = await fetch(`http://127.0.0.1:${server.address().port}/`);
  const cookies = response.headers.getSetCookie().map(parseSetCookie);
  console.table(cookies.map(({ name, httpOnly, secure, sameSite, maxAgeSeconds }) => ({ name, httpOnly, secure, sameSite, maxAgeSeconds })));
  console.log('readable by document.cookie:', visibleToScript(cookies));

  const withCookie = await fetch(`http://127.0.0.1:${server.address().port}/`, {
    headers: { Cookie: 'sid=abc123; theme=dark' },
  });
  console.log(await withCookie.text());

  const deleteHeader = 'sid=; Path=/; Max-Age=0';
  console.log(parseSetCookie(deleteHeader));
  server.close();
  server.closeAllConnections();
});

Run with Node.js v24.22.1 as js-79.js; two runs gave identical output. Output: ┌─────────┬────────────────┬──────────┬────────┬───────────┬───────────────┐ │ (index) │ name │ httpOnly │ secure │ sameSite │ maxAgeSeconds │ ├─────────┼────────────────┼──────────┼────────┼───────────┼───────────────┤ │ 0 │ 'sid' │ true │ true │ 'Lax' │ 3600 │ │ 1 │ 'theme' │ false │ false │ undefined │ 31536000 │ │ 2 │ '__Host-token' │ false │ true │ 'Strict' │ undefined │ └─────────┴────────────────┴──────────┴────────┴───────────┴───────────────┘ readable by document.cookie: theme=dark; __Host-token=t1 you sent: sid=abc123; theme=dark { name: 'sid', value: '', httpOnly: false, secure: false, path: '/', maxAgeSeconds: 0 }

Key points

  • The server sets a cookie with Set-Cookie; the browser returns it in a Cookie header.
  • HttpOnly hides it from scripts; Secure limits it to HTTPS.
  • SameSite (Strict, Lax, None) controls cross-site sending; missing means Lax in browsers.
  • Domain and Path set scope; Max-Age or Expires sets lifetime; Max-Age=0 deletes.
  • Cookies are sent on every matching request, so keep them small.

Common mistakes

  • Storing session tokens in cookies without HttpOnly and Secure.
  • Setting SameSite=None without Secure; browsers reject it.
  • Assuming Domain is optional for sharing with subdomains; leaving it out keeps the cookie host-only.
  • Putting large data in cookies, which is then sent on every request.

Follow-ups

  • How do SameSite=Lax and Strict differ for a link clicked on another site?
  • Why does SameSite not remove the need for CSRF tokens in every case?
  • What is the difference between a session cookie and a persistent cookie?

Tips

  • Name the three security attributes in one breath: HttpOnly, Secure, SameSite.
  • Explain what each protects against: script theft, network sniffing, and cross-site requests.
  • Mention that cookies travel with every request, so size matters.
80.javascript-0080Mediummid

What is cross-site scripting (XSS), and how do you prevent it in front-end JavaScript?

XSS happens when untrusted text is treated as HTML or script in a page, letting an attacker run code in a victim's session. Prevent it by inserting text with textContent, escaping or sanitizing when HTML is unavoidable, validating URL schemes, avoiding dangerous sinks like innerHTML and eval, and adding a Content Security Policy as a second layer.

Full answer

An attacker who can place <script> or an event handler such as <img onerror=...> into your page can read cookies that are not HttpOnly, call APIs as the user, and change what the user sees. There are three kinds. Stored XSS saves the payload in a database and shows it to every visitor, reflected XSS puts it in a link that the server echoes back, and DOM-based XSS happens entirely in the browser when script writes untrusted data into a dangerous place.

The core defense is to treat user data as text unless there is a strong reason not to. element.textContent = value shows the characters literally, even if they look like HTML. Frameworks such as React escape interpolated values for the same reason, and the risky escape hatches (dangerouslySetInnerHTML, v-html) deserve review.

Dangerous sinks include innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, new Function, setTimeout with a string, and setting href or src to untrusted URLs. A link such as javascript:alert(1) runs code, so URLs from users must be parsed and limited to http: and https:.

When user-provided HTML is a real requirement (a rich text editor), sanitize it with a well-maintained library such as DOMPurify or the browser's Sanitizer API where supported, not with a hand-written regular expression. Escaping must match the context: HTML text, an attribute, a URL, and a script each have different rules.

Defense in depth: set a Content Security Policy that blocks inline script and limits script sources, mark session cookies HttpOnly, and validate on the server too, since a client-side check can be bypassed.

javascript
const payload = '<img src="x" onerror="stealCookies()">';

const unsafe = document.createElement('div');
unsafe.innerHTML = payload;
const unsafeImage = unsafe.firstElementChild;
console.log('innerHTML created an element:', unsafeImage.tagName, 'with handler attribute:', unsafeImage.hasAttribute('onerror'));

const safe = document.createElement('div');
safe.textContent = payload;
console.log('textContent children:', safe.children.length, '| shown as text:', safe.textContent === payload);
console.log('serialized:', safe.innerHTML);

function escapeHtml(text) {
  return String(text)
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}
const escaped = escapeHtml(payload);
const viaTemplate = document.createElement('div');
viaTemplate.innerHTML = `<p title="${escapeHtml('" onmouseover="bad()')}">${escaped}</p>`;
console.log('escaped output has no img element:', viaTemplate.querySelector('img') === null);
console.log('attribute stayed one attribute:', viaTemplate.firstElementChild.attributes.length, viaTemplate.firstElementChild.hasAttribute('onmouseover'));

function safeUrl(input) {
  try {
    const url = new URL(input, 'https://example.com');
    return ['http:', 'https:'].includes(url.protocol) ? url.href : null;
  } catch {
    return null;
  }
}
for (const candidate of ['https://school.example/page', '/relative/path', 'javascript:alert(1)', 'JaVaScRiPt:alert(1)', 'data:text/html,<b>x</b>']) {
  console.log(candidate.padEnd(30), '->', safeUrl(candidate));
}

const link = document.createElement('a');
link.href = safeUrl('javascript:alert(1)') ?? '#';
link.textContent = 'profile';
console.log(link.outerHTML);

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: innerHTML created an element: IMG with handler attribute: true textContent children: 0 | shown as text: true serialized: &lt;img src="x" onerror="stealCookies()"&gt; escaped output has no img element: true attribute stayed one attribute: 1 false https://school.example/page -> https://school.example/page /relative/path -> https://example.com/relative/path javascript:alert(1) -> null JaVaScRiPt:alert(1) -> null data:text/html,<b>x</b> -> null <a href="#">profile</a>

Key points

  • XSS lets untrusted input run as script in a victim's session; kinds are stored, reflected, and DOM-based.
  • Prefer textContent and framework escaping over innerHTML.
  • Dangerous sinks: innerHTML, document.write, eval, string timers, and untrusted URLs.
  • Allow only http and https URLs from users.
  • Sanitize required HTML with a vetted library, and add CSP and HttpOnly cookies.

Common mistakes

  • Using innerHTML to insert user text because it is shorter.
  • Blocking only the word script, which misses event-handler attributes and javascript: URLs.
  • Writing a regular expression to sanitize HTML instead of using a vetted library.
  • Trusting client-side checks and skipping server-side validation and output escaping.

Follow-ups

  • How does a Content Security Policy reduce the impact of XSS?
  • What makes DOM-based XSS different from stored XSS?
  • How does React protect against XSS, and when does it not?

Tips

  • Name the three kinds and give one sentence on each.
  • Lead the fix with "treat data as text"; then mention sinks and CSP.
  • Include URL scheme validation; it is a frequent gap.