cs.oldnet

All sheets / Languages

JavaScript

Core language behaviour that comes up in interviews: scope, closures, this, the event loop, and modern syntax.

Variables & scope

ScopeHoistedReassign
varfunctionyes (as undefined)yes
letblockyes (TDZ)yes
constblockyes (TDZ)no (object still mutable)

TDZ = temporal dead zone: accessing let/const before declaration throws ReferenceError.

Types & equality

  • Primitives: string number bigint boolean undefined null symbol. Everything else is an object.
  • typeof null === 'object' (historic bug), typeof [] === 'object', use Array.isArray.
  • == coerces, === doesn't. NaN !== NaN, use Number.isNaN or Object.is.
  • Falsy: false 0 -0 0n "" null undefined NaN.
a ?? b        // b only if a is null/undefined
a || b        // b if a is falsy
obj?.x?.[k]?.() // optional chaining

Closures

A function keeps access to the variables of the scope it was created in.

function counter() {
  let n = 0;
  return () => ++n;
}
const inc = counter(); inc(); inc(); // 2

// classic loop bug: var shares one binding
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 0 1 2

this

Call stylethis
obj.fn()obj
fn()undefined (strict) / globalThis
new Fn()the new instance
fn.call(x) / apply / bindx
arrow functionlexical, from enclosing scope

Event loop

  1. Run the current call stack to completion.
  2. Drain all microtasks (Promise.then, queueMicrotask, await continuations).
  3. Run one macrotask (setTimeout, I/O, UI events), then repeat.
console.log(1);
setTimeout(() => console.log(2));
Promise.resolve().then(() => console.log(3));
console.log(4);   // 1 4 3 2

Promises & async

await Promise.all([a(), b()]);        // fail fast on first reject
await Promise.allSettled([a(), b()]); // never rejects
await Promise.race([p, timeout(500)]); // first to settle
await Promise.any([a(), b()]);        // first to fulfil

async function retry(fn, n = 3) {
  for (let i = 0; ; i++) {
    try { return await fn(); }
    catch (e) { if (i >= n - 1) throw e; await sleep(2 ** i * 100); }
  }
}

Arrays

arr.map(f) .filter(f) .reduce((acc, x) => acc + x, 0)
arr.find(f) .findIndex(f) .some(f) .every(f) .includes(x)
arr.flat(depth) .flatMap(f) .at(-1)
arr.toSorted((a, b) => a - b) // non-mutating (ES2023)
arr.sort()      // mutates, sorts as STRINGS by default
[...new Set(arr)]              // dedupe
Object.groupBy(arr, x => x.type) // ES2024

Objects

const { a, b: renamed, ...rest } = obj;
const copy = { ...obj, x: 1 };        // shallow
const deep = structuredClone(obj);    // deep
Object.entries(o) .keys(o) .values(o) .fromEntries(pairs)
Object.freeze(o)  // shallow immutability

Use Map for frequent add/remove or non-string keys; it keeps insertion order and has .size.

Prototypes & classes

class Animal {
  #secret = 1;            // private field
  static create() { return new this(); }
  speak() { return 'hi'; }
}
class Dog extends Animal {
  speak() { return super.speak() + ' woof'; }
}
Object.getPrototypeOf(new Dog()) === Dog.prototype // true

Classes are sugar over prototype chains: property lookup walks obj -> Proto -> Object.prototype -> null.

Debounce & throttle

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

Modules

// ESM (static, async, tree-shakeable)
import x, { y } from './m.js';
export default x; export const y = 1;
const mod = await import('./lazy.js'); // dynamic

// CommonJS (Node legacy, sync)
const x = require('./m'); module.exports = x;

Gotchas

  • 0.1 + 0.2 !== 0.3, compare with Math.abs(a - b) < Number.EPSILON.
  • [] + {} is "[object Object]", avoid implicit coercion.
  • parseInt('08') is fine, but always pass radix: parseInt(s, 10).
  • JSON.stringify drops undefined, functions, symbols; throws on cycles/BigInt.
  • Arrow functions have no arguments, no prototype, can't be newed.