JavaScript quick reference for interviews

The essentials of the topic on a couple of pages: key concepts by section and the pitfalls interviewers like to ask about.

Types and values

Types.
Seven primitives (string, number, bigint, boolean, undefined, null, symbol) and objects. Arrays, functions and dates are objects too.
Value and reference.
Primitives are immutable and copied by value. Objects are passed by reference: two variables can point to the same object.
typeof.
Returns a string with the type. Quirks: typeof null is "object", typeof function () {} is "function". For arrays use Array.isArray.
== and ===.
=== compares without type conversion. == converts types first, with rules that are hard to remember; the only common exception is x == null for null or undefined.
Falsy values.
false, 0, -0, 0n, "", null, undefined, NaN. Everything else, including [], {} and "0", is truthy.
Numbers.
All numbers are 64-bit floats, so 0.1 + 0.2 is not 0.3. NaN isn't equal to itself: check with Number.isNaN. For big integers use bigint: 10n ** 20n.
?? and ?.
a ?? b takes b only for null or undefined, unlike ||, which also skips 0 and "". user?.address?.city stops at a missing value without an error.

Variables and scope

var, let, const.
let and const are block-scoped, var is function-scoped. const forbids reassignment but doesn't freeze the object: its properties can still change.
Hoisting.
Declarations are processed before the code runs. var is hoisted as undefined, function declarations are hoisted whole, let, const and classes are hoisted without a value.
TDZ.
Until the line with let or const, the variable is in the temporal dead zone: accessing it throws a ReferenceError.
Lexical scope.
A function sees the variables of the place where it was declared, not where it's called. Lookup goes outward to the global scope.
Strict mode.
Modules and classes are always strict: no implicit globals, this in a plain call is undefined, silent errors become exceptions.

Functions and closures

Declaration and expression.
function f() {} is hoisted and can be called before its line. const f = () => {} is available only after the assignment.
Arrow functions.
Shorter syntax, no own this or arguments, can't be called with new. Good for callbacks, not for object methods.
Parameters.
Default values (n = 10) and the rest parameter (...args) replace the old arguments.
Closure.
A function keeps access to variables of the scope where it was created, even after that scope finished. Used for private state, factories and memoization.
Higher-order functions.
Functions take and return functions: map, debounce, decorators, currying.
function createCounter() {
  let count = 0;
  return {
    inc: () => ++count,
    get: () => count,
  };
}

const counter = createCounter();
counter.inc();
counter.inc();
counter.get(); // 2

this

Depends on the call.
this is set at call time: in obj.method() it's obj, in a plain call f() it's undefined in strict mode.
new.
new F() creates an object, links its prototype to F.prototype and calls F with this pointing to it.
call, apply, bind.
f.call(obj, a, b) and f.apply(obj, [a, b]) call with the given this. f.bind(obj) returns a new function with this fixed.
Arrow functions.
Take this from the surrounding code. That's why they're handy inside methods for callbacks.
Lost this.
Passing a method as a callback (setTimeout(user.hi)) detaches it from the object. Use bind or a wrapper () => user.hi().
const user = {
  name: "Ann",
  hi() {
    return this.name;
  },
};

user.hi(); // "Ann"
const hi = user.hi;
hi(); // TypeError: this is undefined
user.hi.bind(user)(); // "Ann"

Objects, prototypes and classes

Prototype chain.
If an object has no property, it's looked up in its prototype, then in the prototype's prototype, up to null. This is how methods are shared.
class.
Syntax over prototypes: constructor, methods, extends and super, static, getters and setters. #field is truly private.
Destructuring and spread.
const { id, ...rest } = obj, [a, b] = [b, a]. { ...obj } and [...arr] make a shallow copy.
Deep copy.
structuredClone(obj) copies nested objects, dates, Map and Set, but not functions or class instances with methods.
Object helpers.
Object.keys, values, entries and fromEntries turn objects into arrays and back. Object.freeze blocks changes, but only one level deep.

Arrays and collections

Transforming.
map, filter, reduce, find, findLast, some, every, flatMap. They don't change the source array.
Mutating methods.
push, pop, splice, sort, reverse change the array in place. Copying versions: toSorted, toReversed, toSpliced, with.
Access and grouping.
arr.at(-1) is the last element. Object.groupBy(items, fn) groups an array into an object by key.
Map and Set.
Map keeps insertion order and accepts any keys, including objects. Set stores unique values and has union, intersection and difference.
WeakMap and WeakSet.
Keys are held weakly: when an object is no longer used elsewhere, the entry is garbage-collected. Good for caches and metadata on objects.
Iteration.
for...of walks any iterable: arrays, strings, Map, Set, generators. for...in walks object keys, including inherited ones.
const orders = [
  { type: "book", total: 120 },
  { type: "food", total: 80 },
  { type: "book", total: 50 },
];

orders.reduce((sum, o) => sum + o.total, 0); // 250
Object.groupBy(orders, (o) => o.type);
// { book: [2 items], food: [1 item] }
orders.toSorted((a, b) => a.total - b.total);

Event loop

Single thread.
JavaScript runs one call stack. While a task is running, nothing else runs, and in the browser the page doesn't respond.
Tasks.
setTimeout, setInterval, events and I/O put callbacks into the task queue. The loop takes them one at a time when the stack is empty.
Microtasks.
Promise callbacks, await continuations and queueMicrotask run right after the current task, all of them, before the next task and before rendering.
setTimeout(fn, 0).
Doesn't run immediately: only after the current code and all microtasks. The delay is a minimum, not a guarantee.
Long tasks.
Heavy computations block the page. Split them into chunks, move them to a Web Worker or yield control with await.
console.log(1);
setTimeout(() => console.log(2));
Promise.resolve().then(() => console.log(3));
queueMicrotask(() => console.log(4));
console.log(5);
// 1 5 3 4 2

Promises and async/await

Promise.
A future result in one of three states: pending, fulfilled or rejected. then, catch and finally return a new promise, so they can be chained.
async/await.
An async function always returns a promise. await pauses the function, not the thread. Errors are caught with try/catch.
Combinators.
Promise.all fails at the first error, allSettled waits for all and returns statuses, race takes the first finished one, any takes the first successful one.
Parallel and sequential.
await in a loop runs requests one by one. Independent ones are started together: await Promise.all(ids.map(load)).
Cancellation.
AbortController cancels fetch and listeners: pass controller.signal and call controller.abort().
Unhandled rejection.
A rejected promise without catch or await gives an unhandledrejection warning in the browser and can crash Node.js.
async function loadAll(ids) {
  const results = await Promise.allSettled(
    ids.map((id) => fetch(`/api/items/${id}`)),
  );
  return results.filter((r) => r.status === "fulfilled");
}

Modules

ES modules.
export and import with named and default exports. Imports are static, so bundlers can remove unused code (tree shaking).
Live bindings.
An import is a live view of the exported variable, not a copy, and it can't be reassigned from outside.
Dynamic import.
await import("./chart.js") loads a module on demand and returns a promise. Used for code splitting.
CommonJS.
require and module.exports in older Node.js code: loaded synchronously and evaluated at call time. New code uses ES modules.
In the browser.
<script type="module"> is deferred by default, runs in strict mode and has its own scope. Top-level await works in modules.

Patterns and memory

debounce and throttle.
Debounce waits for a pause in events (search input), throttle runs at most once per interval (scroll, resize).
Event delegation.
One listener on a parent handles events from children through event.target.closest(...), including ones added later.
Memoization.
Caches a function's result by its arguments, usually in a Map inside a closure.
Garbage collection.
An object is removed when it's no longer reachable from the roots: global variables, the stack, active closures.
Memory leaks.
Listeners and timers that are never removed, growing caches and global variables keep objects alive. Remove listeners and clear timers.
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

Common pitfalls

  • typeof null === "object": check for null separately.
  • [1, 10, 2].sort() sorts as strings and gives [1, 10, 2]. Pass a comparator: sort((a, b) => a - b).
  • 0.1 + 0.2 === 0.3 is false. Compare with a tolerance or work in whole cents.
  • == with type conversion: [] == false and "" == 0 are true. Use ===.
  • var in a loop with setTimeout prints the last value three times. let creates a new variable on each iteration.
  • A method passed as a callback loses this: setTimeout(user.hi).
  • forEach with an async callback doesn't wait for it. Use for...of with await or Promise.all.
  • { ...obj } copies only one level: nested objects stay shared.
  • ["1", "2", "3"].map(parseInt) gives [1, NaN, NaN]: the index is passed as the radix.
  • A forgotten await returns a promise instead of the value, and an error inside it goes unhandled.

Cheat sheet