All sheets / Languages
JavaScript
Core language behaviour that comes up in interviews: scope, closures, this, the event loop, and modern syntax.
Variables & scope
| Scope | Hoisted | Reassign | |
|---|---|---|---|
var | function | yes (as undefined) | yes |
let | block | yes (TDZ) | yes |
const | block | yes (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', useArray.isArray.==coerces,===doesn't.NaN !== NaN, useNumber.isNaNorObject.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 chainingClosures
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 2this
| Call style | this |
|---|---|
obj.fn() | obj |
fn() | undefined (strict) / globalThis |
new Fn() | the new instance |
fn.call(x) / apply / bind | x |
| arrow function | lexical, from enclosing scope |
Event loop
- Run the current call stack to completion.
- Drain all microtasks (
Promise.then,queueMicrotask,awaitcontinuations). - 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 2Promises & 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) // ES2024Objects
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 immutabilityUse 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 // trueClasses 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 withMath.abs(a - b) < Number.EPSILON.[] + {}is"[object Object]", avoid implicit coercion.parseInt('08')is fine, but always pass radix:parseInt(s, 10).JSON.stringifydropsundefined, functions, symbols; throws on cycles/BigInt.- Arrow functions have no
arguments, noprototype, can't benewed.