BTI Beyond The Interviews

Languages · 12 sections

JavaScript

The syntax, methods and gotchas that show up in almost every JS screening round.

Free · full sheet 131 cards Updated 24 Oct 2026

Types & Coercion

Primitive types in JS

Seven primitives: string, number, bigint, boolean, undefined, symbol, null. Everything else (including arrays, functions) is an object. typeof null === 'object' is a historic bug.

typeof 'a'        // 'string'
typeof 42         // 'number'
typeof 10n        // 'bigint'
typeof true       // 'boolean'
typeof undefined  // 'undefined'
typeof Symbol()   // 'symbol'
typeof null       // 'object'  (historic bug)
typeof []         // 'object'
typeof function(){} // 'function'

typeof null is 'object'

A bug from the first JS implementation (tagged pointers); never fixed for web compat. Check null explicitly: value === null. Use Object.prototype.toString for reliable type tags.

Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call([])   // '[object Array]'

NaN checks

NaN is the only value not equal to itself. Use Number.isNaN (no coercion) rather than global isNaN (coerces). Also NaN is a number type.

NaN === NaN           // false
Number.isNaN(NaN)      // true
Number.isNaN('abc')    // false (no coercion)
isNaN('abc')           // true  (coerces to NaN)
typeof NaN             // 'number'

== vs ===

=== compares value and type with no coercion. == coerces operands to a common type first. Prefer ===; == is only occasionally useful (null == undefined).

'1' == 1            // true  (coerces)
'1' === 1           // false
null == undefined   // true
null === undefined  // false
0 == false          // true
0 === false         // false

Falsy values

Only eight falsy values: false, 0, -0, 0n, '', null, undefined, NaN. Everything else is truthy — including '0', 'false', [], {}.

Boolean(0)        // false
Boolean('0')       // true
Boolean([])        // true
Boolean({})        // true
if (arr.length) { /* non-empty */ }

Number() vs parseInt() vs +

Number() converts whole string strictly (NaN if trailing garbage). parseInt parses prefix and accepts radix. Unary + is like Number. parseFloat for floats.

Number('42px')     // NaN
parseInt('42px', 10) // 42
+'42'              // 42
parseInt('08')     // 8 (always pass radix 10!)
Number('')         // 0
Number(null)       // 0

0.1 + 0.2 !== 0.3

IEEE-754 double precision cannot represent 0.1 exactly. Use integer cents or toFixed/rounding for money. Compare with epsilon for floats.

0.1 + 0.2            // 0.30000000000000004
0.1 + 0.2 === 0.3     // false
(0.1 + 0.2).toFixed(2) // '0.30'
Math.abs((0.1+0.2)-0.3) < Number.EPSILON // true

String to number coercion in arithmetic

+ triggers numeric coercion; other operators (-,*,/) coerce too but + concatenates if either operand is string. Beware mixed types.

'5' + 3     // '53' (concatenation)
'5' - 3     // 2   (numeric)
'5' * '2'   // 10
[] + {}     // '[object Object]'
{} + []     // 0 (statement context)

null and undefined coercion

Number(null)=0, Number(undefined)=NaN. In arithmetic null becomes 0. undefined propagates NaN. Check explicitly to avoid surprises.

null + 5        // 5
undefined + 5    // NaN
null == 0        // false (== special case)
null >= 0        // true  (numeric coercion)

Object to primitive coercion

ToPrimitive: valueOf then toString. {} becomes '[object Object]'. [] becomes '' (valueOf returns [] then toString). Date uses toString first.

String({})   // '[object Object]'
String([])    // ''
Number([])    // 0
Number({})    // NaN
[] + 1       // '1' (string concat after coercion)

BigInt cannot mix with Number

BigInt and Number cannot be mixed in arithmetic without explicit conversion. Comparisons (==, <) are allowed and coerce. JSON.stringify throws on BigInt.

1n + 2       // TypeError
1n + 2n       // 3n
1n == 1       // true
1n === 1      // false
JSON.stringify(1n) // TypeError

Symbol uniqueness and coercion

Every Symbol() is unique. Symbols are not auto-converted to strings in concatenation (throws TypeError). Use .toString() or .description.

Symbol('a') === Symbol('a') // false
Symbol('a') + 'x'            // TypeError
String(Symbol('a'))          // 'Symbol(a)'
Symbol('a').description      // 'a'

Variables & Scope

var vs let vs const

Prefer const by default, let when reassignment needed. var is function-scoped and hoisted (initialized undefined). let/const are block-scoped with TDZ. const prevents reassignment but objects/arrays still mutable.

const x = 1;   // block-scoped, no reassign
let y = 2;     // block-scoped, reassignable
var z = 3;     // function-scoped (legacy)
const arr = []; arr.push(1); // OK — mutation allowed

Hoisting

Declarations are hoisted but initializers are not. var hoisted as undefined; function declarations fully hoisted; let/const hoisted into TDZ (access before declaration throws). Function declarations are fully hoisted; function expressions (including arrow) are not hoisted as values (const/let TDZ applies).

console.log(a); // undefined (var hoisted)
var a = 5;
foo();           // works (function hoisted)
function foo() {}
console.log(b); // ReferenceError (TDZ)
let b = 5;

Temporal Dead Zone (TDZ)

let/const exist in scope from block start but cannot be accessed until declaration line. Accessing throws ReferenceError, not undefined. typeof in TDZ also throws.

{
  // TDZ for x starts here
  console.log(typeof x); // ReferenceError
  let x = 1;
}

Block scope

let/const are confined to nearest enclosing braces (if/for/block). var leaks out of blocks (except function). This is why for-loops with var share one binding.

if (true) { let a = 1; var b = 2; }
console.log(typeof a); // undefined (ReferenceError if accessed)
console.log(b);        // 2 (leaked)

Function scope

var is scoped to the enclosing function (or global). Nested functions create new scopes. Parameters are function-scoped. No block scope for var.

function f() {
  if (true) { var x = 1; }
  console.log(x); // 1
}

Closure basics

A function retains access to its lexical scope even after that scope exits. Basis of private state, memoization, partial application, and module pattern.

function counter() {
  let n = 0;
  return () => ++n;
}
const c = counter();
c(); // 1
c(); // 2 // n is private

Loop closures with var bug

var in a for-loop creates one shared binding; all callbacks see final value. Fix with let (per-iteration binding) or IIFE capturing current value.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0); // 3 3 3
}
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0); // 0 1 2
}

Global object and global scope

Top-level var in browser becomes window property; let/const do not. In modules, top-level declarations are module-scoped, not global. globalThis is universal global reference.

var g = 1; console.log(window.g); // 1 (browser, non-module)
let l = 2; console.log(window.l); // undefined
globalThis.setTimeout;

Lexical scoping

Scope is determined by source code structure, not call site. Inner functions can access outer variables; outer cannot access inner. Shadowing allowed. Inner function scope chain: own locals, then enclosing, then global; nearest binding wins. Shadowing creates a new binding.

const x = 'outer';
function f() { const x = 'inner'; console.log(x); }
f(); // 'inner'
console.log(x); // 'outer'

Destructuring assignment and scope

Destructuring creates new bindings in current scope. const/let apply to all destructured names. Default values only apply for undefined, not null.

const { a, b = 2 } = { a: 1 }; // b=2
const [x, y] = [10, 20];
const { name: n } = obj; // rename
let a, b; ({ a, b } = obj); // needs parens in statement

Functions

Arrow vs regular function

Arrow functions have no own this, arguments, super, or prototype; cannot be used as constructors. They inherit this lexically. Regular functions bind this at call time. obj.arrow() returns the enclosing this (globalThis in a classic script, undefined in a module).

const obj = {
  n: 1,
  regular() { return this.n; },
  arrow: () => this // lexical this, not obj
};
obj.regular(); // 1
obj.arrow();   // globalThis in a script, undefined in a module

this binding rules

this is determined by call site: method call (obj.method), standalone (undefined in strict, global otherwise), new (new instance), explicit (call/apply/bind). Arrow functions ignore these.

function f() { return this.x; }
const o = { x: 42 };
f.call(o);     // 42
f.apply(o);    // 42
const bound = f.bind(o); bound(); // 42

call, apply, bind

call invokes with this and args list; apply with args array; bind returns new function with fixed this (and optional partial args). bind creates permanent binding.

fn.call(ctx, a, b);
fn.apply(ctx, [a, b]);
const bound = fn.bind(ctx, a); // partial
bound(b);

Default parameters

Evaluated at call time, can reference earlier params and variables. Default applies only when argument is undefined (not null).

function f(a, b = a * 2, c = (x => x)(b)) {
  return [a, b, c];
}
f(3);      // [3,6,6]
f(3, null); // [3, null, null] (null not default)

Rest parameters

Collects remaining arguments into a real Array. Must be last param. Replaces arguments object in arrows. Rest in destructuring too.

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
const [first, ...rest] = [1, 2, 3]; // rest=[2,3]

Spread operator

Expands iterable into elements/properties. Use for array copy/merge, object clone/merge, function args. Creates shallow copies.

const t = [...arr, 4];
const copy = { ...obj };
const merged = { ...a, ...b }; // b wins conflicts
Math.max(...nums);

arguments object

Array-like (not Array) available in regular functions. Contains all passed args. Arrow functions have no arguments; use rest params. arguments is legacy and discouraged in favor of rest parameters, but not deprecated.

function f() { return [...arguments]; }
f(1, 2); // [1,2]
// arrow: (...args) => args

IIFE

Immediately Invoked Function Expression: (function(){...})(). Creates private scope. Common pre-ES6 modules. Still used for async IIFE and avoiding global pollution.

(function() {
  const secret = 42;
})();
(async () => {
  await init();
})();

Higher-order functions

Functions that take or return functions. map/filter/reduce are HOFs. Enables composition, currying, partial application, callbacks.

const compose = (f, g) => x => f(g(x));
const add1 = x => x + 1;
const double = x => x * 2;
compose(double, add1)(3); // 8

Currying and partial application

Currying transforms f(a,b) into f(a)(b). Partial application fixes some args. Useful for reusable, composable functions and event handlers.

const curry = f => a => b => f(a, b);
const add = curry((a, b) => a + b);
const add5 = add(5);
add5(3); // 8

Recursion and tail calls

JS engines do not reliably optimize tail calls (spec has TCO but rarely implemented). Deep recursion risks stack overflow; prefer iteration or trampolining.

function fact(n, acc = 1) {
  if (n <= 1) return acc;
  return fact(n - 1, n * acc); // not guaranteed TCO
}

Objects & Prototypes

__proto__ vs prototype

__proto__ is the instance's link to its prototype (accessor on Object.prototype). prototype is a property of constructor functions used when creating instances via new. Object.getPrototypeOf(obj) is preferred.

function Foo() {}
const o = new Foo();
o.__proto__ === Foo.prototype; // true
Object.getPrototypeOf(o) === Foo.prototype; // true

Prototype chain lookup

Property access walks the chain: own props, then prototype, then its prototype, until null. Assignment creates own property unless setter on prototype. in operator checks whole chain.

const o = {};
o.toString(); // found on Object.prototype
'hasOwnProperty' in o; // true
o.hasOwnProperty('x'); // checks own only

Object.create

Creates object with specified prototype (or null). Enables pure prototypal inheritance without constructors. Object.create(null) makes dict without Object.prototype methods.

const proto = { greet() { return 'hi ' + this.name; } };
const o = Object.create(proto);
o.name = 'Ada';
o.greet(); // 'hi Ada'
Object.create(null); // no toString/hasOwnProperty

hasOwnProperty

Checks if property is own (not inherited). Prefer Object.hasOwn(obj, key) (ES2022) to avoid prototype shadowing issues. in operator includes inherited.

const o = Object.create({ x: 1 });
o.y = 2;
o.hasOwnProperty('y'); // true
o.hasOwnProperty('x'); // false
Object.hasOwn(o, 'y'); // true

Property descriptors

Properties have value/writable/enumerable/configurable (data) or get/set (accessor). Define with Object.defineProperty. Non-enumerable props (like methods) won't show in for...in/keys.

Object.defineProperty(obj, 'id', {
  value: 1, writable: false,
  enumerable: false, configurable: false
});
Object.getOwnPropertyDescriptor(obj, 'id');

Getters and setters

Accessor properties run functions on read/write. Defined in object literal with get/set or via defineProperty. Useful for validation, computed values, reactivity.

const user = {
  first: 'Ada', last: 'Lovelace',
  get full() { return this.first + ' ' + this.last; },
  set full(v) { [this.first, this.last] = v.split(' '); }
};

Object.keys / values / entries

keys/values/entries return arrays of own enumerable string-keyed properties. For arrays, indices as strings. Object.entries enables Object.fromEntries for transform.

Object.keys({ a: 1, b: 2 }); // ['a','b']
Object.values({ a: 1, b: 2 }); // [1,2]
Object.fromEntries([['a',1],['b',2]]); // {a:1,b:2}

Shallow vs deep copy

Spread/assign create shallow copies: nested objects shared. Object.create does not copy anything; it sets the prototype. Deep clone via structuredClone (modern) — but it throws on functions/DOM nodes and drops class prototypes — or JSON (loses functions/dates/undefined).

const shallow = { ...obj };
const proto = Object.create(obj); // sets prototype, no copy
const deep = structuredClone(obj); // throws on fn/DOM, drops prototypes
const jsonClone = JSON.parse(JSON.stringify(obj)); // loses Date, fn, undefined

Object.freeze vs seal

freeze: no add/remove/change (shallow). seal: no add/remove but values writable. Both shallow. Use for immutability of top level only.

const o = Object.freeze({ nested: { x: 1 } });
o.nested.x = 2; // allowed (shallow)
o.y = 3;        // silently fails (strict: TypeError)

Classes and private fields

ES6 class is sugar over prototypes. constructor, methods, static, getters/setters, extends/super. Private fields use # and are truly private (hard private).

class Animal {
  #secret = 42;
  constructor(name) { this.name = name; }
  speak() { return `${this.name} speaks`; }
  static create(n) { return new Animal(n); }
  get info() { return this.name; }
}

instanceof and constructor

instanceof checks prototype chain. constructor property can be reassigned. Use instanceof for same-realm; cross-realm/frame use Array.isArray etc.

[] instanceof Array; // true
[] instanceof Object; // true
Array.isArray([]);    // true (robust cross-realm)

Mixins and composition

JS favors composition over inheritance. Mixins: Object.assign(target, mixin) or class mixins via subclass factory. Avoid deep inheritance hierarchies.

const withLog = Base => class extends Base {
  log(msg) { console.log(msg); }
};
class Foo extends withLog(Object) {}

Arrays & Iteration

map / filter / reduce

Core transforms: map 1:1, filter keeps subset, reduce folds to single value. All return new (reduce returns accumulator). Chainable. Prefer over manual loops.

const nums = [1,2,3,4];
nums.map(n => n * 2);           // [2,4,6,8]
nums.filter(n => n % 2 === 0);  // [2,4]
nums.reduce((a,n) => a+n, 0);  // 10

forEach vs map

forEach executes callback for side effects, returns undefined. map returns new array of transformed values. Don't use map for side effects; don't use forEach when you need result.

arr.forEach(x => console.log(x)); // side effects
const doubled = arr.map(x => x * 2); // transform

find vs filter vs some vs every vs includes

find: first match or undefined. filter: all matches. some: any match (bool). every: all match (bool). includes: value equality (NaN-aware). findIndex returns index.

[1,2,3].find(n => n > 1);   // 2
[1,2,3].filter(n => n > 1); // [2,3]
[1,2,3].some(n => n > 2);   // true
[1,2,3].every(n => n > 0);  // true
[NaN].includes(NaN);         // true

splice vs slice

splice mutates (remove/insert at index, returns removed). slice non-mutating (returns subarray copy). splice(start, deleteCount, ...items).

const a = [1,2,3,4];
a.splice(1, 2, 9); // a=[1,9,4], returns [2,3]
[1,2,3,4].slice(1, 3); // [2,3] (non-mutating)

sort gotcha

Default sort converts to strings and sorts UTF-16. Numbers sort wrong without comparator. sort mutates. Use toSorted (ES2023) for non-mutating.

[10, 2, 1].sort();              // [1,10,2]
[10, 2, 1].sort((a,b)=>a-b);     // [1,2,10]
[3,1,2].toSorted((a,b)=>a-b);    // [1,2,3] (non-mutating)

flat and flatMap

flat(depth=1) flattens nested arrays. flatMap maps then flattens one level (efficient combo). Useful for filtering + mapping.

[1,[2,[3]]].flat();        // [1,2,[3]]
[1,[2,[3]]].flat(2);        // [1,2,3]
[1,2,3].flatMap(x => [x, x*2]); // [1,2,2,4,3,6]

Destructuring arrays

Positional extraction with defaults and rest. Skipping with commas. Swapping without temp via destructuring.

const [a, b, c = 3] = [1, 2];
const [first, , third] = arr; // skip
let x = 1, y = 2; [x, y] = [y, x]; // swap

Array holes and sparse arrays

Arrays can be sparse (holes). forEach/map/filter/reduce skip holes; map preserves them in the output, filter removes them; for...of/spread treat holes as undefined. length can exceed actual elements. Avoid; holes cause weird behavior.

const a = [1, , 3]; // hole at index 1
a.length; // 3
a.map(x => x * 2); // [2, empty, 6]
[...a]; // [1, undefined, 3]
Array(3); // [empty x3]

Array.from and Array.of

Array.from converts array-like/iterable to array, with optional map. Array.of creates array from args (fixes Array(n) single-arg hole issue).

Array.from('abc');            // ['a','b','c']
Array.from({ length: 3 }, (_, i) => i); // [0,1,2]
Array.of(5);                   // [5] (not [empty x5])

reduce patterns

Grouping is now built in: Object.groupBy(items, x => x.type) / Map.groupBy (ES2024). reduce still useful for sum, flatten, pipe. Initial value important for empty arrays (otherwise throws).

Object.groupBy(items, x => x.type); // ES2024
Map.groupBy(items, x => x.type);   // preserves key types
[1,2,3].reduce((a,n)=>a+n,0); // 6
items.reduce((acc, x) => {
  (acc[x.type] ??= []).push(x);
  return acc;
}, {});

at() method

arr.at(-1) returns last element (negative indexing). Works on strings too. Cleaner than arr[arr.length-1].

[1,2,3].at(-1);  // 3
[1,2,3].at(0);    // 1
'abc'.at(-1);     // 'c'

Iterating: for...of vs for...in

for...of iterates iterable values (arrays, strings, maps, sets). for...in iterates enumerable string keys (including inherited) — avoid for arrays. Use Object.keys or for...of.

for (const v of arr) { } // values
for (const k in obj) { }  // keys (incl inherited)
for (const [k,v] of Object.entries(obj)) { }

Closures & Scope

Module pattern

IIFE returning object with public methods, private state in closure. Pre-ES6 modules. Revealing module pattern exposes selected internals.

const Module = (function() {
  let privateVar = 0;
  function privateFn() { return ++privateVar; }
  return { increment: privateFn, get: () => privateVar };
})();

Private variables via closure

Closure hides state; only exposed functions can access. No external mutation. Basis of encapsulation before private fields.

function makeBank(initial) {
  let balance = initial;
  return {
    deposit: (n) => (balance += n),
    getBalance: () => balance
  };
}

Closure in event handlers

Handlers capture variables from creation scope. Stale closures in loops cause bugs; use let or bind current value. Common in React useEffect.

buttons.forEach((btn, i) => {
  btn.onclick = () => console.log(i); // captures i correctly with let/block
});

Memoization with closure

Cache function results in closure. Key by all arguments (serialized or a composite key). Trade memory for speed.

function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const v = fn(...args);
    cache.set(key, v);
    return v;
  };
}

Partial application via closure

Fix some arguments now, return function expecting rest. Useful for configuring generic functions (e.g., fetch with base URL).

const fetchFrom = (base) => (path) =>
  fetch(base + path);
const api = fetchFrom('/api');
api('/users');

Closure and memory leaks

Closures keep referenced outer variables alive. Large objects captured unintentionally prevent GC. Nullify references or restructure to allow collection.

function big() {
  const data = new Array(1e6);
  return () => data.length; // keeps data alive
}

Factory functions

Function returning object with methods closing over parameters. Alternative to classes; favors composition and privacy. No 'this' binding issues.

const makeCounter = (start = 0) => {
  let n = start;
  return {
    inc: () => ++n,
    dec: () => --n,
    value: () => n
  };
};

Late binding in closures

Closures capture variable bindings, not values. If variable changes later, closure sees new value. Common bug in loops and callbacks.

let x = 1;
const f = () => x;
x = 2;
f(); // 2 (sees current binding)

Async & Event Loop

Event loop order

Synchronous code first, then microtasks (promises, queueMicrotask, MutationObserver), then macrotasks (setTimeout, setInterval, I/O). Microtasks drain fully before next macrotask.

console.log('A');
setTimeout(() => console.log('C')); // macrotask
Promise.resolve().then(() => console.log('B')); // microtask
// Output: A B C

Microtasks vs macrotasks

Microtasks: promise callbacks, queueMicrotask, MutationObserver. In Node, process.nextTick runs before promise microtasks. Macrotasks: setTimeout, setInterval, setImmediate, I/O. UI rendering is a separate rendering step between tasks, not a macrotask. Microtasks have higher priority.

queueMicrotask(() => console.log('micro'));
setTimeout(() => console.log('macro'), 0);
// micro then macro (browser)
// Node: process.nextTick runs before Promise microtasks

Promise states

Promise: pending, fulfilled, or rejected. Once settled, immutable. .then/.catch/.finally return new promises, enabling chaining.

const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve(42), 100);
});
p.then(v => v * 2).then(console.log); // 84

Promise.all vs allSettled vs race vs any

all: reject-fast, all must fulfill. allSettled: never rejects, reports each status. race: first to settle wins. any: first fulfillment wins, ignores rejections (AggregateError if all reject).

await Promise.all([p1, p2]);         // reject if any rejects
await Promise.allSettled([p1, p2]); // always resolves
await Promise.race([p1, p2]);       // first settle
await Promise.any([p1, p2]);        // first success

async/await basics

async function returns promise. await pauses until promise settles. Syntactic sugar over promises; improves readability. Errors propagate as rejections.

async function load() {
  const res = await fetch('/api');
  if (!res.ok) throw new Error(res.status);
  return res.json();
}

Parallel vs sequential awaits

Sequential awaits run one after another (slower). Parallelize independent work with Promise.all. Dependent calls must be sequential.

// sequential (slow)
const u = await getUser(id);
const p = await getPosts(u.id);
// parallel (fast)
const [user, posts] = await Promise.all([getUser(id), getPosts(id)]);

Error handling with async/await

Wrap in try/catch. Unhandled rejections can crash. .catch on promise chain. finally for cleanup. Promise.all does not cancel the other promises — they keep running; you just lose their results. Use allSettled to collect every outcome.

try {
  const data = await fetchJson(url);
} catch (e) {
  console.error('failed', e);
} finally {
  hideSpinner();
}
// allSettled collects all outcomes without short-circuiting

Promise chaining return values

.then callback return value becomes next promise's resolution. Return a promise to chain async. .catch catches upstream rejection; .finally runs regardless and doesn't change value unless throws.

fetch('/api')
  .then(r => r.json())
  .then(data => process(data))
  .catch(err => showError(err))
  .finally(() => hideSpinner());

setTimeout and 0 delay

setTimeout(fn, 0) schedules macrotask; doesn't run immediately. Minimum delay ~4ms in browsers after nesting. Used to defer work, yield to event loop.

console.log('start');
setTimeout(() => console.log('timeout'), 0);
console.log('end');
// start, end, timeout

Fetch API basics

fetch returns promise resolving to Response. Check res.ok (fetch doesn't reject on HTTP errors). Body methods (json/text) consume stream once. Use AbortController to cancel.

const ctrl = new AbortController();
const res = await fetch(url, { signal: ctrl.signal });
if (!res.ok) throw new Error(res.status);
const data = await res.json();
// ctrl.abort() to cancel

Promise constructor anti-pattern

Don't wrap existing promises in new Promise. Use promise directly. The 'deferred' pattern (external resolve/reject) is now standardized as Promise.withResolvers() (ES2024) — use it as the legitimate way when you really need external resolve/reject. Avoid new Promise around async operations that already return promises.

// bad
new Promise((resolve) => { resolve(fetch(url)); });
// good
fetch(url);
// deferred when truly needed (ES2024)
const { promise, resolve, reject } = Promise.withResolvers();

queueMicrotask

Schedules microtask. Use instead of setTimeout(0) for microtask timing. Runs before rendering/macrotasks. Useful for batching state updates.

queueMicrotask(() => {
  // runs after current sync code, before macrotasks
});

DOM & Browser

Event bubbling and capturing

Events propagate in three phases: capture (down to target), target, bubble (up). addEventListener third arg true = capture. stopPropagation stops further propagation.

parent.addEventListener('click', handler, true); // capture
child.addEventListener('click', handler); // bubble
e.stopPropagation();

Event delegation

Attach single listener to parent; use e.target to identify origin. Efficient for dynamic lists. Check closest() for robust matching.

list.addEventListener('click', (e) => {
  const item = e.target.closest('li');
  if (item) handle(item.dataset.id);
});

localStorage vs sessionStorage

localStorage persists across tabs/sessions until cleared (~5-10MB). sessionStorage scoped to tab, cleared on close. Both sync, string-only (JSON serialize). Warning: storing tokens (e.g. JWT) in localStorage exposes them to any XSS. Prefer HttpOnly, Secure, SameSite cookies for tokens.

// Avoid storing tokens in localStorage (XSS-readable)
// localStorage.setItem('token', jwt); // risky
sessionStorage.setItem('draft', JSON.stringify(obj));
// Prefer HttpOnly Secure SameSite cookies for auth tokens

preventDefault vs stopPropagation

preventDefault cancels default action (form submit, link nav). stopPropagation stops event bubbling/capturing. stopImmediatePropagation also stops other handlers on same element.

form.addEventListener('submit', (e) => {
  e.preventDefault(); // no page reload
  submitData();
});

IntersectionObserver

Async observe element visibility/intersection with viewport. Efficient lazy loading, infinite scroll, analytics. Callback fires on threshold crossing.

const io = new IntersectionObserver((entries) => {
  entries.forEach(e => {
    if (e.isIntersecting) load(e.target);
  });
}, { threshold: 0.5 });
io.observe(img);

MutationObserver

Watches DOM changes (childList, attributes, subtree). Async, batched. Use for reacting to DOM mutations without polling.

const mo = new MutationObserver((mutations) => {
  for (const m of mutations) console.log(m.type);
});
mo.observe(node, { childList: true, subtree: true });

ResizeObserver

Observes element size changes (not just window). Better than window resize for component-level responsiveness.

const ro = new ResizeObserver((entries) => {
  for (const e of entries) console.log(e.contentRect.width);
});
ro.observe(container);

requestAnimationFrame

Schedules callback before next repaint at the display refresh rate (60/120/144 Hz, not a fixed ~60fps). Paused in background tabs. Use for animations, visual updates. Better than setTimeout for smooth rendering. Cancel with cancelAnimationFrame.

function animate() {
  update();
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

Custom events

Dispatch custom events with new CustomEvent(type, { detail }). Listen with addEventListener. Useful for decoupled component communication.

const ev = new CustomEvent('user:login', { detail: { id: 1 } });
document.dispatchEvent(ev);
document.addEventListener('user:login', (e) => console.log(e.detail));

dataset and data attributes

data-* attributes exposed via element.dataset (camelCase). Read/write. Good for storing config/ids on elements for delegation.

<li data-user-id="42" data-role="admin"></li>
el.dataset.userId; // '42'
el.dataset.role = 'member';

getBoundingClientRect and layout

getBoundingClientRect returns viewport-relative position/size. Triggers layout (reflow) if called in loop — batch reads/writes to avoid thrashing.

const rect = el.getBoundingClientRect();
console.log(rect.top, rect.width);

querySelector vs getElementById

querySelector uses CSS selectors (first match). getElementById is faster and by id only. querySelectorAll returns static NodeList. Prefer querySelector for flexibility.

document.querySelector('.card.active');
document.getElementById('app');
document.querySelectorAll('li.item'); // static NodeList

ES6+ Features

Template literals

Backticks allow interpolation ${}, multi-line strings, tagged templates. Tagged templates enable DSL (styled-components, SQL sanitization).

const name = 'Ada';
const msg = `Hello, ${name}!
Line two.`;
sql`SELECT * FROM users WHERE id = ${id}`; // tagged

Destructuring objects with defaults and rename

Pull values with fallbacks (undefined only). Rename with colon. Nested destructuring. Default params in functions often use this.

const { name, age = 18, address: { city } = {} } = user;
const fn = ({ id, name = 'anon' }) => `${id}:${name}`;

Optional chaining ?.

Short-circuits to undefined if null/undefined encountered. Works for properties, calls, indexing. Avoids verbose && chains. Doesn't short-circuit other falsy.

const city = user?.address?.city;
const len = arr?.length;
const res = obj.method?.(); // safe call
user?.[key];

Nullish coalescing ??

Returns right operand only if left is null/undefined (not other falsy like 0, ''). Unlike ||. Combine with optional chaining for defaults. Falsy includes 0 and '' which may be valid values; use ?? for null/undefined defaults, not ||, to avoid overwriting legitimate falsy values.

const port = config.port ?? 3000; // 0 stays 0
const name = user.name ?? 'anon'; // '' stays ''
const x = a?.b ?? 'default';

Logical assignment operators

&&=, ||=, ??= assign only if condition holds. Concise conditional assignment. ??= only if null/undefined.

x &&= transform(x); // if x truthy
y ||= defaultValue;  // if y falsy
z ??= 0;             // if z null/undefined

Static blocks and initialization

static {} runs once on class definition. Useful for complex static init. Static fields can reference earlier statics.

class C {
  static x = 1;
  static y;
  static { this.y = this.x * 2; }
}

Top-level await (ESM)

await at module top level; module becomes async. Dependent modules wait. Enables simpler async init. Only in ESM.

// config.mjs
const res = await fetch('/config.json');
export const config = await res.json();

WeakMap and WeakSet

Keys must be objects; held weakly (no prevent GC). Use for private data, memoization, DOM metadata. Not iterable, no size.

const privates = new WeakMap();
class Foo {
  constructor() { privates.set(this, { secret: 42 }); }
  getSecret() { return privates.get(this).secret; }
}

Symbol and well-known symbols

Symbols as unique keys (non-enumerable by default). Well-known symbols (Symbol.iterator, Symbol.asyncIterator, Symbol.toPrimitive) customize language behavior.

const id = Symbol('id');
obj[id] = 123;
// iterable:
class Range {
  *[Symbol.iterator]() { for (let i=this.start;i<=this.end;i++) yield i; }
}

Modules: dynamic import

import() returns promise, enables code splitting and conditional loading. Use for lazy loading routes/components. Works in CJS and ESM.

const { default: Chart } = await import('./chart.js');
if (needFeature) {
  const mod = await import('./feature.js');
}

Numeric separators and BigInt

Underscores in numeric literals improve readability (1_000_000). BigInt for arbitrary precision integers (1n). Cannot mix with Number in arithmetic.

const billion = 1_000_000_000;
const hex = 0xFF_FF;
const big = 9007199254740993n; // exact

Common Gotchas & Interview Tricks

Array equality

Arrays compared by reference, not contents. [1,2] === [1,2] is false. Compare via JSON.stringify or deep equality (lodash isEqual).

[1,2] === [1,2]; // false
JSON.stringify([1,2]) === JSON.stringify([1,2]); // true

delete operator

delete removes own property (returns true). On array creates hole (doesn't change length). Cannot delete var/let/const. Use splice or set undefined instead.

const o = { a: 1 }; delete o.a; // true
const arr = [1,2,3]; delete arr[1]; // [1, empty, 3], length still 3

with statement

with extends scope chain with object. Deprecated, forbidden in strict mode, breaks optimization. Never use.

'use strict';
with (obj) { x = 1; } // SyntaxError in strict mode

eval and security

eval executes string as code in current scope. Security risk, blocks optimization, slow. Avoid both eval and the Function constructor — both run arbitrary strings and are blocked by the same CSP unsafe-eval rule. Parse data with JSON.parse, or use a lookup table or a real parser. Indirect eval runs in global scope.

// avoid: eval('1+1'); // 2
// avoid: const f = new Function('a', 'return a+1');
// instead:
const data = JSON.parse(str);
const handlers = { add: (a,b) => a+b };
handlers[op]?.(a, b);

Automatic semicolon insertion (ASI)

JS inserts semicolons in certain positions. Can cause bugs: return on next line returns undefined; leading ( or [ on new line treated as continuation.

function f() {
  return
    { a: 1 }; // returns undefined!
}
// fix: return { a: 1 }; on same line

Comma operator

Evaluates operands left to right, returns last. Rarely useful; can confuse. Used in for-loop increments and one-liners.

const x = (1, 2, 3); // 3
for (let i=0, j=10; i<j; i++, j--) {}

Object key coercion

Object keys are strings (or symbols). Numbers become strings ('1'). {1: 'a'}[1] works due to coercion. Map preserves key types.

const o = { 1: 'a' };
o[1]; // 'a'
o['1']; // 'a'
const m = new Map(); m.set(1, 'a'); m.get(1); // 'a'; m.get('1') // undefined

Promise unhandled rejection

A rejected promise with no .catch can crash Node (unhandledRejection) or log warning in browser. Always handle. Use process.on('unhandledRejection') as safety net.

Promise.reject(new Error('x')); // unhandled
// fix:
Promise.reject(new Error('x')).catch(console.error);

Advanced Topics (Gaps)

Generators and iterator protocol

A generator function (function*) returns an iterator. The iterator protocol requires a next() returning {value, done}. Generators support yield, yield*, and two-way communication via next(arg)/throw/return. for...of consumes iterables via Symbol.iterator.

function* range(n) {
  for (let i = 0; i < n; i++) yield i;
}
const it = range(3);
it.next(); // {value:0, done:false}
for (const v of range(3)) console.log(v);
// iterable protocol: obj[Symbol.iterator] = function* () { ... }

Proxy and Reflect

Proxy wraps a target and intercepts operations via traps (get, set, has, deleteProperty, apply, construct, ...). Reflect provides default implementations for each trap. Use for validation, reactivity, virtualization. Revocable proxies via Proxy.revocable.

const p = new Proxy({}, {
  get(t, k) { return k in t ? t[k] : 0; },
  set(t, k, v) { if (typeof v !== 'number') throw TypeError(); t[k] = v; return true; }
});
p.x = 5; p.y; // 0
const { proxy, revoke } = Proxy.revocable({}, {}); revoke();

ESM vs CommonJS

ESM uses import/export, is statically analyzable, supports top-level await, and has live bindings. CommonJS uses require/module.exports, is dynamic, and caches modules by resolved path. ESM files use .mjs or type:module; interop allows import of CJS with default import.

// ESM
import { x } from './m.js';
export const y = x + 1;
// CJS
const x = require('./m');
module.exports = { y: x + 1 };
// dynamic
const m = await import('./m.js');

Debounce and throttle implementation

Debounce delays invocation until calls stop for wait ms (leading/trailing options). Throttle limits invocation to at most once per wait ms. Implement with timers and saved args/this; clear on cancel.

function debounce(fn, wait) {
  let t;
  return (...args) => {
    clearTimeout(t);
    t = setTimeout(() => fn(...args), wait);
  };
}
function throttle(fn, wait) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= wait) { last = now; fn(...args); }
  };
}

Web Workers

Web Workers run scripts in background threads, communicating via postMessage/structured clone. No DOM access. Use for CPU-heavy work; transferables (ArrayBuffer) avoid copying. SharedArrayBuffer + Atomics for shared memory; requires COOP/COEP headers.

// main.js
const w = new Worker('worker.js');
w.postMessage({ data }, [buf]); // transfer
w.onmessage = (e) => console.log(e.data);
// worker.js
self.onmessage = (e) => { self.postMessage(compute(e.data)); };

Garbage collection, WeakRef and FinalizationRegistry

JS uses tracing GC (mark-and-sweep). WeakRef holds a weak reference to an object that can be collected; deref() returns undefined after collection. FinalizationRegistry runs a cleanup callback after an object is collected. Do not rely on timing for correctness.

const ref = new WeakRef(obj);
ref.deref(); // obj or undefined
const reg = new FinalizationRegistry((held) => console.log('collected', held));
reg.register(obj, 'token');

ES2024–2025 features: Set methods, Iterator helpers, Array.fromAsync, RegExp v flag

Set gained union/intersection/difference/symmetricDifference and subset/superset/disjoint (ES2025). Iterator helpers (map/filter/take/drop/reduce/toArray) (ES2025). Array.fromAsync (ES2024) for async iterables. RegExp v flag (ES2024) enables set notation and properties of strings.

new Set([1,2]).union(new Set([2,3])); // Set {1,2,3}
[1,2,3].values().map(x=>x*2).toArray(); // [2,4,6]
await Array.fromAsync(asyncGen()); // array
/^[\p{Letter}]+$/v.test('café');

Temporal API

Temporal (stage 4, shipping in browsers/Node) replaces Date with immutable, timezone-aware types: PlainDate, PlainTime, ZonedDateTime, Instant, Duration. Avoids mutation and DST pitfalls. Use for robust date/time logic.

const d = Temporal.PlainDate.from('2026-10-23');
const z = Temporal.Now.zonedDateTimeISO('America/New_York');
const dur = Temporal.Duration.from({ days: 1 });
d.add(dur); // new PlainDate

Error cause and AggregateError

Error accepts options: new Error('msg', { cause: err }) for chaining. AggregateError wraps multiple errors (Promise.any, or manual). Use cause for context without losing stack; check err.cause.

try { await load(); } catch (e) {
  throw new Error('load failed', { cause: e });
}
throw new AggregateError([e1, e2], 'multiple failures');
// err.errors holds the array

CORS basics

Cross-Origin Resource Sharing: browser blocks cross-origin reads unless server sends Access-Control-Allow-Origin (and credentials handling). Preflight OPTIONS for non-simple requests. CORS is a browser policy; server-to-server calls are unaffected. Use credentials: 'include' with Access-Control-Allow-Credentials.

// server
res.setHeader('Access-Control-Allow-Origin', 'https://app.example');
res.setHeader('Access-Control-Allow-Credentials', 'true');
// client
fetch(url, { credentials: 'include' });

structuredClone and AbortSignal.timeout

structuredClone deep-clones supported values (Date, Map, Set, ArrayBuffer) but throws on functions/DOM nodes and drops prototypes. AbortSignal.timeout(ms) returns a signal that aborts after ms; combine with AbortSignal.any([...]) (ES2024) for multiple abort sources.

const copy = structuredClone({ d: new Date(), m: new Map() });
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
const sig = AbortSignal.any([ctrl.signal, AbortSignal.timeout(1000)]);

Regex Essentials

Feature support by engine

Python re: backrefs, lookaround, fixed-width lookbehind, plus atomic groups and possessive quantifiers from 3.11. PCRE2: everything plus conditionals, recursion and (10.43+) bounded variable lookbehind. Java: backrefs, bounded lookbehind, atomic groups, possessive quantifiers; no conditionals or recursion. .NET: backrefs, unbounded lookbehind, conditionals, atomic groups. JavaScript: backrefs, unbounded lookbehind, scoped modifiers (?ims:...) from ES2025, but no atomic groups or possessives. Go RE2 / Rust regex: none of the advanced constructs.

# check the feature against the engine you will actually ship on

JS matchAll and replaceAll

String.prototype.matchAll (ES2020) returns an iterator of match objects (groups, and indices with the d flag) and requires a global regex — otherwise it throws. replaceAll (ES2021) replaces every occurrence; with a regex it must have g, otherwise TypeError. Replacement tokens: $1, $<name>, $& (whole match), plus the dollar-backtick and dollar-quote tokens for the text before/after the match.

[...'a1b2'.matchAll(/(?<l>\w)(?<d>\d)/g)]
'a1b2'.replaceAll(/\d/g, '#')                    // 'a#b#'
'a1b2'.replace(/(?<l>\w)(?<d>\d)/g, '$<d>$<l>')  // '1a2b'

split and findall return groups

If the split pattern contains capturing groups, Python's re.split includes the captured text in the result — use (?:...) when you don't want it. re.findall returns group contents only: a list of strings with one group, a list of tuples with several, and whole matches when there are none. Use finditer for spans and named groups. JavaScript's String.split also keeps captured separators.

re.split(r'(\d+)', 'a1b2')    # ['a', '1', 'b', '2', '']
re.split(r'(?:\d+)', 'a1b2')  # ['a', 'b', '']
re.findall(r'(\w)(\d)', 'a1')  # [('a', '1')]

Whole-string matching: fullmatch vs matches()

re.search finds a match anywhere; re.match anchors at the start only; re.fullmatch (Python 3.4+) requires the whole string. Java's Matcher.matches() is whole-string while find() searches (Pattern.matches is a one-shot matches()). Go's MatchString is unanchored, so anchor explicitly with \A...\z. Note $ can match before a trailing newline — prefer fullmatch/\z for validation.

re.fullmatch(r'\d+', s)                      # Python
Pattern.compile("\\d+").matcher(s).matches()  # Java
/^\d+$/.test(s)                              # JS (no trailing newline)

u — unicode

Treats the pattern and subject as Unicode code points, enables \p{...}, and makes . match astral characters as one unit in JavaScript. Python 3 str patterns are Unicode by default, so inline (?u) is redundant there — and JavaScript has no u modifier at all (its scoped modifiers cover only i/m/s), so pass u/v on the regex itself. Use re.ASCII to opt out in Python.

/\p{L}+/u                    // JS
re.compile(r'\w+')             # Python 3: already Unicode
re.compile(r'\w+', re.ASCII)   # opt out

Regex timeouts

.NET lets you pass a timeout to the Regex constructor and throws RegexMatchTimeoutException. Java has no built-in timeout: run the match in an executor with Future.get(timeout), or use an interruptible CharSequence. Python re has no timeout either — the third-party regex module accepts timeout=. Go/Rust RE2-style engines cannot blow up, so they need no timeout.

new Regex(pattern, RegexOptions.None, TimeSpan.FromSeconds(1));  // .NET
regex.search(p, s, timeout=1.0)  # Python regex module

Fixed-width lookbehind

Python re requires fixed-width lookbehind: every alternative must have the same length, so (?<=ab|cd) is fine but (?<=a|bc) is an error. PCRE2 requires fixed length by default (10.43+ allows bounded variable length) and Java requires a bounded maximum length, while .NET, JavaScript (ES2018+) and Python's third-party regex module allow unbounded variable width.

(?<=ab|cd)x    # ok in Python re
(?<=a|bc)x    # error: look-behind requires fixed-width pattern
(?<=colou?r)  # ok in JS, Java, .NET, PCRE2 10.43+

Backtracking vs linear-time engines

PCRE, JavaScript, Java, .NET, Python re and Ruby backtrack: they support backreferences and lookaround but can go exponential (ReDoS). Go's regexp and Rust's regex crate use finite automata (RE2/Thompson NFA): guaranteed linear time, but no backreferences, lookaround, conditionals or recursion. Choose an RE2-style engine for untrusted input.

regexp.MustCompile(`\d{3}-\d{4}`)   // Go
Regex::new(r"\d{3}-\d{4}")?        // Rust

Combining flags inline

Use (?ims) to enable flags for the rest of the pattern, or (?i:abc) to scope them to a group. Supported by PCRE, Python, Java, .NET and Perl. JavaScript (ES2025) supports only the scoped form (?ims-ims:...) — there is no bare (?i), so whole-pattern flags still go on the literal or the RegExp constructor.

(?i:cat)dog              # cat case-insensitive only
new RegExp('cat', 'i')   // JS equivalent

Recursion (?R) and (?1)

(?R) re-applies the whole pattern and (?1) re-applies group 1, which lets an engine match arbitrarily nested structures. Supported by PCRE and Perl (Ruby/Oniguruma uses subexpression calls instead); not by Python re, JavaScript, Java, .NET or RE2. For nested HTML/JSON, use a parser.

\((?:[^()]|(?R))*\)   # balanced parentheses (PCRE)

Atomic group (?>...)

An atomic group locks in its match and disables backtracking into it. Equivalent to a possessive quantifier over the group, and the portable way to stop catastrophic backtracking when the engine supports it. Python 3.11+ supports (?>...); older Python can use the regex module.

(?>\d+)px   # digits then px, no backtrack

Escaping inside character classes

Inside [] most metacharacters are literal; only \, ], ^ (first position) and - (between characters) need care. JavaScript differs: [] is an empty class that never matches, so a literal leading ] must be escaped there; in PCRE, Python and Java a leading ] is taken literally.

[\]\\^-]   # JS: matches ], \, ^, -
[]\\^-]   # PCRE/Python/Java: same, unescaped ] first

Want this as flashcards? Study these 131 cards recall-first in the browser — flip, answer out loud, grade yourself.

Open the card deck