devsetswww.devsets.com/en/topics/javascript/notes
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 nullis"object",typeof function () {}is"function". For arrays useArray.isArray. - == and ===.
===compares without type conversion.==converts types first, with rules that are hard to remember; the only common exception isx == nullfornullorundefined.- 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.2is not0.3.NaNisn't equal to itself: check withNumber.isNaN. For big integers usebigint:10n ** 20n. - ?? and ?.
a ?? btakesbonly fornullorundefined, unlike||, which also skips0and"".user?.address?.citystops at a missing value without an error.
Variables and scope
- var, let, const.
letandconstare block-scoped,varis function-scoped.constforbids reassignment but doesn't freeze the object: its properties can still change.- Hoisting.
- Declarations are processed before the code runs.
varis hoisted asundefined, function declarations are hoisted whole,let,constand classes are hoisted without a value. - TDZ.
- Until the line with
letorconst, the variable is in the temporal dead zone: accessing it throws aReferenceError. - 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,
thisin a plain call isundefined, 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
thisorarguments, can't be called withnew. Good for callbacks, not for object methods. - Parameters.
- Default values
(n = 10)and the rest parameter(...args)replace the oldarguments. - 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(); // 2this
- Depends on the call.
thisis set at call time: inobj.method()it'sobj, in a plain callf()it'sundefinedin strict mode.- new.
new F()creates an object, links its prototype toF.prototypeand callsFwiththispointing to it.- call, apply, bind.
f.call(obj, a, b)andf.apply(obj, [a, b])call with the giventhis.f.bind(obj)returns a new function withthisfixed.- Arrow functions.
- Take
thisfrom 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. Usebindor 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,extendsandsuper,static, getters and setters.#fieldis 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,MapandSet, but not functions or class instances with methods.- Object helpers.
Object.keys,values,entriesandfromEntriesturn objects into arrays and back.Object.freezeblocks 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,reversechange 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.
Mapkeeps insertion order and accepts any keys, including objects.Setstores unique values and hasunion,intersectionanddifference.- 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...ofwalks any iterable: arrays, strings,Map,Set, generators.for...inwalks 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,
awaitcontinuations andqueueMicrotaskrun 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 2Promises and async/await
- Promise.
- A future result in one of three states: pending, fulfilled or rejected.
then,catchandfinallyreturn a new promise, so they can be chained. - async/await.
- An
asyncfunction always returns a promise.awaitpauses the function, not the thread. Errors are caught withtry/catch. - Combinators.
Promise.allfails at the first error,allSettledwaits for all and returns statuses,racetakes the first finished one,anytakes the first successful one.- Parallel and sequential.
awaitin a loop runs requests one by one. Independent ones are started together:await Promise.all(ids.map(load)).- Cancellation.
AbortControllercancelsfetchand listeners: passcontroller.signaland callcontroller.abort().- Unhandled rejection.
- A rejected promise without
catchorawaitgives anunhandledrejectionwarning 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.
exportandimportwith 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.
requireandmodule.exportsin 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-levelawaitworks 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
Mapinside 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 fornullseparately.[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.3isfalse. Compare with a tolerance or work in whole cents.==with type conversion:[] == falseand"" == 0aretrue. Use===.varin a loop withsetTimeoutprints the last value three times.letcreates a new variable on each iteration.- A method passed as a callback loses
this:setTimeout(user.hi). forEachwith anasynccallback doesn't wait for it. Usefor...ofwithawaitorPromise.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
awaitreturns a promise instead of the value, and an error inside it goes unhandled.