JS Interview Kit
JSInterview Kit

This kit helps you get ready for fresher and junior JavaScript interviews. Everything here is plain JavaScript. No frameworks and no libraries.

How to use it

  • Learn tab: short lessons, one at a time. Open the browser console (press F12) and type the code yourself. Typing teaches more than reading.
  • Practice tab: questions with hidden answers. Say your answer out loud first, then open the answer. Tick the ones you can answer.
  • Lessons marked Must know are asked in almost every interview.

A 5-day plan

DayWhat to study
1Foundations, scope, hoisting, closures
2this, prototypes, classes, arrays, objects
3Event loop, callbacks, promises, async/await
4DOM and events, browser APIs, modules, level up
5Practice tab: output questions and coding questions, then repeat the ones you missed

A simple way to answer any question

  1. Define it in one sentence.
  2. Show a tiny example, even if you only write it in the air or on paper.
  3. Add one real use or one common mistake. This is what makes you sound experienced.
Say in interviewIf you do not know something, say what you do know and how you would find out. "I have not used that, but I would check the MDN page" is a good answer. Guessing with confidence is a bad one.

JavaScript is a high-level, dynamically typed language. It runs inside an engine: V8 in Chrome and Node.js, SpiderMonkey in Firefox, JavaScriptCore in Safari.

Key facts

  • Single-threaded. There is one call stack, so only one piece of code runs at a time.
  • Dynamically typed. Variables have no type. Values have types. let x = 1; x = "hi"; is fine.
  • JIT compiled. The engine turns your code into bytecode and speeds up hot code while the program runs. So it is not purely "interpreted".
  • Multi-paradigm. You can write object-oriented, functional, or simple step-by-step code.
  • ECMAScript is the official standard. JavaScript follows it. A new version comes every year. ES2015 (ES6) was the big one.

Engine and runtime are different

PartWhat it gives you
Engine (V8)Reads and runs JavaScript. Has the memory heap and the call stack.
Runtime (browser or Node.js)Adds extra tools: DOM, fetch, timers in the browser; fs, http in Node.js. Also runs the event loop.
Say in interviewsetTimeout and fetch are not part of the JavaScript language. The runtime provides them.

Strict mode

Strict mode turns silent mistakes into errors. Modules and classes are strict by default.

'use strict';
x = 5; // ReferenceError: x is not defined (without strict mode this makes a global!)

Three ways to declare a variable. Today you use const and let. You still need to know var because interviewers love to ask about it.

varletconst
ScopeFunctionBlock { }Block { }
HoistedYes, value is undefinedYes, but in the dead zoneYes, but in the dead zone
RedeclareAllowedErrorError
ReassignYesYesNo
Becomes window property (global)YesNoNo

Temporal dead zone (TDZ)

A let or const variable exists from the start of its block, but you cannot touch it until the line where it is declared. The time before that line is the TDZ.

console.log(a); // undefined (var is hoisted with undefined)
var a = 1;

console.log(b); // ReferenceError (TDZ)
let b = 2;

The classic loop problem

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

var has one i for the whole function. let makes a new j for every loop turn, so each callback keeps its own value.

const does not mean "frozen"

const user = { name: 'Sara' };
user.name = 'Ali';  // allowed, the object changed
user = {};          // TypeError, you cannot point user to a new object
Say in interviewI use const by default, let when the value must change, and I avoid var.

JavaScript has 7 primitive types and one object type. Many bugs come from not knowing how values are converted.

The types

  • Primitives: string, number, bigint, boolean, undefined, null, symbol.
  • Objects: everything else. Arrays, functions, dates, maps, and plain objects.
typeof 'hi'          // 'string'
typeof 42            // 'number'
typeof NaN           // 'number'
typeof undefined     // 'undefined'
typeof null          // 'object'   (an old bug that stays for compatibility)
typeof []            // 'object'   (use Array.isArray([]) instead)
typeof function(){}  // 'function'

By value or by reference

Primitives are copied by value. Objects are copied by reference, which means two variables can point to the same object.

let a = 5;
let b = a;
b = 10;
console.log(a); // 5

const p = { n: 1 };
const q = p;      // same object, not a copy
q.n = 99;
console.log(p.n); // 99

Equality: == and ===

  • === (strict) compares value and type. No conversion.
  • == (loose) converts types first, which gives surprises.
5 === '5'          // false
5 == '5'           // true
null == undefined  // true
null === undefined // false
NaN === NaN        // false (NaN is not equal to itself)
Number.isNaN(NaN)  // true, the right way to check
Object.is(NaN, NaN) // true

Coercion examples

'5' + 2        // '52'  (+ with a string joins)
'5' - 2        // 3     (- always makes numbers)
true + 1       // 2
[] + []        // ''
[] + {}        // '[object Object]'
0.1 + 0.2      // 0.30000000000000004 (floating point)

Falsy values

Only 8 values are falsy: false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy, including "0", [] and {}.

Common mistakeChecking if (count) when 0 is a valid value. Use count !== undefined or count ?? default.

A few modern operators make code shorter and safer. Interviewers like to check that you know them.

|| and ??

const count = 0;
count || 10   // 10  (0 is falsy, so || moves on)
count ?? 10   // 0   (?? only reacts to null and undefined)

let name;
name ??= 'Guest';   // assign only if name is null or undefined
let on = false;
on ||= true;        // assign if falsy
let ready = true;
ready &&= false;   // assign if truthy

Optional chaining ?.

Stops and gives undefined when something in the path is missing, instead of throwing an error.

const city = user?.address?.city;
const first = list?.[0];
user.greet?.();           // calls greet only if it exists

Short-circuit

isLoggedIn && showDashboard();   // runs only if isLoggedIn is truthy
const label = title || 'Untitled'; // first truthy value wins

Template literals and ternary

const msg = `Hello ${user.name}, you have ${n} message${n === 1 ? '' : 's'}`;

Loops

for (const item of [10, 20]) {}       // values of an iterable (arrays, strings, Map, Set)
for (const key in { a: 1, b: 2 }) {}  // keys of an object (do not use on arrays)
while (cond) {}
[1, 2, 3].forEach(n => console.log(n));

break and continue work in for and while loops. They do not work inside forEach.

In JavaScript, functions are values. You can store them in variables, pass them to other functions, and return them. This is called "first-class functions".

Three ways to write one

function add(a, b) { return a + b; }          // declaration (hoisted)
const add2 = function (a, b) { return a + b; }; // expression (not hoisted)
const add3 = (a, b) => a + b;                  // arrow (short, implicit return)

Parameters

function greet(name = 'friend') { return `Hi ${name}`; }  // default value
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } // rest: collects the rest into an array
sum(1, 2, 3);        // 6
sum(...[4, 5, 6]);   // 15  (spread: opens an array into arguments)

Arrow functions are different

  • No own this. They use the this of the place where they were written.
  • No arguments object.
  • Cannot be used with new.
  • Not good as object methods or prototype methods because of the this rule.

Higher-order functions and callbacks

A higher-order function takes a function or returns a function. A callback is a function you pass to be called later.

const double = n => n * 2;
[1, 2, 3].map(double);   // map is higher-order, double is the callback

function multiplier(x) { return n => n * x; }  // returns a function
multiplier(3)(5); // 15

IIFE

An Immediately Invoked Function Expression runs right away and keeps its variables private.

(function () {
  const secret = 42;
  console.log('runs once');
})();

Pure functions

A pure function always gives the same output for the same input and changes nothing outside itself. They are easy to test and reason about.

Scope decides where a variable can be used. JavaScript uses lexical scope: the scope is decided by where you write the code, not where you call it.

Kinds of scope

  • Global: outside all functions and blocks.
  • Function: inside a function. var, let and const are all private to it.
  • Block: inside { }. Only let and const respect it.
  • Module: each ES module file has its own top-level scope.

Scope chain

When JavaScript looks for a variable, it checks the current scope first, then the parent scope, and so on up to the global scope. The first match wins.

inner() scopehas c. Looks here first.
outer() scopehas b. Checked second.
Global scopehas a. Checked last. Not found anywhere gives ReferenceError.
const a = 'global';
function outer() {
  const b = 'outer';
  function inner() {
    const c = 'inner';
    console.log(a, b, c); // inner can see all three
  }
  inner();
}
outer();
// console.log(b) here would throw, outer's variables are private

Shadowing

let x = 'outside';
{
  let x = 'inside';   // a new variable that hides the outer one
  console.log(x);     // 'inside'
}
console.log(x);       // 'outside'
Say in interviewA function remembers the scope where it was defined. That is exactly what makes closures work.

Before JavaScript runs your code, it reads through it once and sets up memory for your variables and functions. People call this "hoisting". Nothing is really moved. The declarations are just known early.

What each one does

DeclarationBefore its line runs
function foo() {}Fully usable. The whole function is hoisted.
var x = 1Exists with value undefined.
let / constExists but in the TDZ. Using it throws ReferenceError.
classSame as let. TDZ.
Function expression (var f = function(){})f is undefined, so calling it throws TypeError.
console.log(a);            // undefined
var a = 5;

console.log(sayHi());      // 'hi'  (function declaration works early)
function sayHi() { return 'hi'; }

console.log(typeof sayBye); // 'undefined'
var sayBye = function () {};

sayBye2();                 // TypeError: sayBye2 is not a function
var sayBye2 = function () {};

Execution context and call stack

Every time a function runs, JavaScript creates an execution context. It has two phases: first creation (set up variables, hoisting, this), then execution (run the lines). The call stack holds these contexts. The last one in is the first one out.

function a() { b(); }
function b() { c(); }
function c() { console.log('hi'); }
a();
// stack grows: global, a, b, c ... then shrinks back as each one returns
Common mistakeA function that calls itself with no end fills the stack and throws RangeError: Maximum call stack size exceeded (stack overflow).

A closure is a function that remembers the variables from the place where it was created, even after that outer function has finished.

function makeCounter() {
  let count = 0;             // private, nobody outside can touch it
  return function () {
    count++;
    return count;
  };
}
const next = makeCounter();
next(); // 1
next(); // 2
const other = makeCounter();
other(); // 1  (its own separate count)

When makeCounter ends, you might expect count to disappear. It does not, because the returned function still uses it. The engine keeps that variable alive.

Why closures are useful

  • Private data: keep a variable hidden and give access only through functions.
  • Function factories: multiplier(3) returns a function that remembers 3.
  • Callbacks and event handlers: they remember the data they need.
  • Memoization, debounce, once: all use a closure to remember state.

Closure inside a loop

// Problem: all callbacks share one i
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3

// Fix 1: use let (new i for each turn)
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 0 1 2

// Fix 2: older way, wrap in a function to capture the value
for (var j = 0; j < 3; j++) {
  (function (k) { setTimeout(() => console.log(k)); })(j);
}
Watch outA closure keeps its variables in memory. A big object captured by a long-living closure (for example an event listener you never remove) can cause a memory leak.
Say in interview"A closure is a function together with the lexical environment it was created in." Then show the counter example.

this is decided by how a function is called, not where it is written. The only exception is the arrow function, which takes this from the place where it was written.

The four rules

// 1. Plain call: undefined in strict mode (window in sloppy mode)
function show() { console.log(this); }
show();

// 2. Method call: this is the object before the dot
const user = { name: 'Sara', hi() { console.log(this.name); } };
user.hi();   // 'Sara'

// 3. Explicit: you choose this with call, apply or bind
function greet(greeting) { return greeting + ', ' + this.name; }
greet.call(user, 'Hello');      // 'Hello, Sara'
greet.apply(user, ['Hello']);   // same, but arguments in an array
const bound = greet.bind(user); // returns a NEW function, does not call it
bound('Hi');                    // 'Hi, Sara'

// 4. new: this is the brand new object
function Person(name) { this.name = name; }
new Person('Ali').name;  // 'Ali'
MethodCalls the function now?Arguments
callYesOne by one
applyYesAs an array
bindNo, returns a new functionOne by one (can pre-fill some)

Losing this

'use strict';
const user = { name: 'Sara', hi() { console.log(this.name); } };
const f = user.hi;   // we took the function out of the object
f();                 // TypeError: this is undefined
setTimeout(user.hi, 0); // same problem

setTimeout(() => user.hi(), 0);   // fix 1: call it as a method inside an arrow
setTimeout(user.hi.bind(user), 0); // fix 2: bind

Arrow functions

const timer = {
  seconds: 0,
  start() {
    setInterval(() => {
      this.seconds++;   // arrow uses this of start(), which is timer
    }, 1000);
  }
};

Do not use an arrow function as an object method. const o = { x: 1, get: () => this.x } does not work, because this is not o.

Say in interviewAsk yourself "who is on the left of the dot when it is called?" If nobody, it is the default rule. If it is an arrow, look outside.

Every object has a hidden link to another object called its prototype. If a property is not found on the object, JavaScript looks in its prototype, then the prototype's prototype, until it reaches null. This is the prototype chain.

rexown property: name
animalhas speak()
Object.prototypehas toString(), hasOwnProperty()
nullend of the chain
const animal = { speak() { return this.name + ' makes a sound'; } };
const rex = Object.create(animal);   // rex's prototype is animal
rex.name = 'Rex';
rex.speak();                         // 'Rex makes a sound' (found on animal)
rex.toString();                      // found on Object.prototype

Object.getPrototypeOf(rex) === animal; // true
rex.hasOwnProperty('speak');           // false, it is inherited
Object.hasOwn(rex, 'name');            // true (modern way)

prototype vs __proto__

  • __proto__ (or Object.getPrototypeOf) is the link that every object has.
  • prototype is a property that only functions have. It is the object given as the link to instances made with new.
function Dog(name) { this.name = name; }
Dog.prototype.bark = function () { return this.name + ' says woof'; };

const d = new Dog('Max');
d.__proto__ === Dog.prototype;   // true
[].__proto__ === Array.prototype; // true
d.bark();                         // methods are shared, not copied for each dog

What new does

  1. Creates an empty object.
  2. Links its prototype to Constructor.prototype.
  3. Runs the constructor with this set to that object.
  4. Returns the object (unless the constructor returns another object).
Say in interviewJavaScript has no real classes underneath. It has objects that link to other objects. The class keyword is a cleaner way to write the same thing.

ES6 class is a cleaner syntax on top of prototypes. Same system, nicer look.

class Animal {
  #energy = 10;                 // private field, only usable inside the class
  static count = 0;             // belongs to the class, not to instances

  constructor(name) {
    this.name = name;
    Animal.count++;
  }
  speak() { return `${this.name} makes a sound`; }   // goes on Animal.prototype
  get energy() { return this.#energy; }              // getter
  eat() { this.#energy += 5; }
  static create(name) { return new Animal(name); }
}

class Dog extends Animal {
  constructor(name) {
    super(name);                // must call super() before using this
    this.type = 'dog';
  }
  speak() { return super.speak() + ' (woof)'; }  // override and reuse parent
}

const d = new Dog('Rex');
d.speak();            // 'Rex makes a sound (woof)'
d instanceof Animal;  // true
d.energy;             // 10
// d.#energy          // SyntaxError, it is private

Things to remember

  • typeof Animal is 'function'. Classes are functions.
  • Classes are not usable before the declaration (TDZ), unlike function declarations.
  • Class code always runs in strict mode.
  • Methods lose this when passed as callbacks. Use an arrow function or bind.
  • extends sets up the prototype chain for you.

Arrays are ordered lists. Most interview coding questions use map, filter and reduce, so know them well.

The big three

const nums = [1, 2, 3, 4, 5];

nums.map(n => n * 2);             // [2, 4, 6, 8, 10]  new array, same length
nums.filter(n => n % 2 === 0);    // [2, 4]            keeps items that return true
nums.reduce((sum, n) => sum + n, 0); // 15            folds everything into one value

// chaining
nums.filter(n => n > 2).map(n => n * 10);  // [30, 40, 50]

reduce gets an accumulator and the current item. The second argument (0) is the starting value. Always give it, or an empty array will throw an error.

Find things

nums.find(n => n > 2);       // 3 (first match, or undefined)
nums.findIndex(n => n > 2);  // 2 (or -1)
nums.some(n => n > 4);       // true  (at least one)
nums.every(n => n > 0);      // true  (all of them)
nums.includes(3);            // true
nums.indexOf(3);             // 2
nums.at(-1);                 // 5 (last item)

Mutating or not?

Changes the original arrayReturns a new array
push, pop, shift, unshift, splice, sort, reverse, fillmap, filter, slice, concat, flat, flatMap, spread [...arr], and the newer toSorted, toReversed, toSpliced, with

Useful bits

[1, [2, [3]]].flat(Infinity);   // [1, 2, 3]
Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2]
Array.isArray([]);              // true
[...new Set([1, 1, 2])];        // [1, 2] removes duplicates

[10, 9, 1].sort();              // [1, 10, 9]  default sort compares as STRINGS
[10, 9, 1].sort((a, b) => a - b); // [1, 9, 10]  numbers: pass a compare function

forEach returns nothing and you cannot stop it early. Use for...of when you need break, or map when you want a new array.

Objects store key-value pairs. Modern JavaScript gives you short ways to read, build and copy them.

Writing and reading

const key = 'age';
const user = {
  name: 'Sara',
  [key]: 22,                 // computed key
  greet() { return 'Hi ' + this.name; }  // method shorthand
};
const name = 'Ali', city = 'Lahore';
const person = { name, city }; // shorthand for { name: name, city: city }

Object.keys(user);     // ['name', 'age', 'greet']
Object.values(user);
Object.entries(user);  // [['name','Sara'], ...]
Object.fromEntries([['a', 1], ['b', 2]]); // { a: 1, b: 2 }

Destructuring and spread

const { name: n, age = 18, address: { city: c } = {} } = user; // rename, default, nested
const [first, , third, ...others] = [1, 2, 3, 4, 5];
[a, b] = [b, a];                 // swap

const merged = { ...defaults, ...options }; // later keys win
const copy = [...arr, 6];

Shallow copy vs deep copy

Spread and Object.assign copy only the first level. Nested objects are still shared.

const a = { name: 'Sara', tags: ['x'] };
const shallow = { ...a };
shallow.tags.push('y');
console.log(a.tags);       // ['x', 'y']  the nested array is shared!

const deep = structuredClone(a);   // real deep copy (modern browsers and Node 17+)
const old = JSON.parse(JSON.stringify(a)); // old trick: loses functions, undefined, Dates become strings

Protecting objects

const o = Object.freeze({ x: 1, inner: { y: 2 } });
o.x = 5;        // ignored (throws in strict mode)
o.inner.y = 9;  // works! freeze is shallow

Object.seal lets you change values but not add or remove keys. const only stops reassigning the variable. freeze stops changing the object.

Built-in tools that often give a cleaner answer than a plain object or array.

Map and Set

const m = new Map();
m.set('a', 1).set({ id: 1 }, 'any type can be a key');
m.get('a'); m.has('a'); m.size; m.delete('a');
for (const [k, v] of m) {}      // keeps insertion order

const s = new Set([1, 2, 2, 3]); // { 1, 2, 3 } unique values only
s.add(4); s.has(2); s.size;
MapPlain object
Keys can be anythingKeys are strings or symbols
Has .sizeCount with Object.keys(o).length
No inherited keysInherits from Object.prototype
Fast add and removeGood for fixed, known shapes

WeakMap / WeakSet: keys must be objects and are held weakly. If nothing else uses the object, it can be garbage collected. Good for private data and caches.

JSON

JSON.stringify({ a: 1, b: undefined, c: () => 1, d: new Date(0) });
// '{"a":1,"d":"1970-01-01T00:00:00.000Z"}'  undefined and functions are dropped

JSON.parse('{"a":1}');   // { a: 1 }
JSON.parse('{bad json}'); // throws SyntaxError, so use try/catch

Symbol and Date

  • Symbol('id') makes a unique value. Two symbols are never equal. Used for hidden keys and special protocols like Symbol.iterator.
  • new Date() months start at 0 (January is 0). Date.now() gives milliseconds since 1970.

JavaScript has one call stack, yet it can wait for timers and network calls without freezing. The event loop is the reason.

1. Call stackYour code runs here, one function at a time.
2. Web APIsTimers, fetch and DOM events wait here, outside the stack.
3. QueuesWhen work is done, the callback waits in a queue.
4. Event loopWhen the stack is empty, it moves the next callback onto it.

Two queues, one rule

  • Microtask queue: promise .then, await continuation, queueMicrotask.
  • Task (macrotask) queue: setTimeout, setInterval, click events, network events.
  • Rule: after each task, the loop empties all microtasks before it takes the next task.
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// 1  4  3  2

Why: 1 and 4 are plain code, so they run first. The promise callback is a microtask, so it runs before the timer callback, which is a task.

Common mistakesetTimeout(fn, 0) does not mean "now". It means "after the current code and all microtasks are done". Also, a heavy loop blocks everything, including clicks and rendering.
Say in interview"JavaScript is single-threaded but not blocking, because slow work is handed to the runtime and its callback comes back through the event loop."

A callback is a function you give to another function to run later. It was the first way to handle async work in JavaScript.

setTimeout(() => console.log('after 1 second'), 1000);
const id = setInterval(() => console.log('every second'), 1000);
clearInterval(id);        // always stop intervals you no longer need

[1, 2, 3].forEach(n => console.log(n)); // this callback is synchronous

Not every callback is async. forEach calls its callback right away. setTimeout calls it later.

Callback hell

When each step needs the result of the previous one, callbacks nest deeper and deeper. The code becomes hard to read and error handling is repeated everywhere.

getUser(id, (err, user) => {
  if (err) return handle(err);
  getOrders(user.id, (err, orders) => {
    if (err) return handle(err);
    getDetails(orders[0], (err, details) => {
      if (err) return handle(err);
      console.log(details);
    });
  });
});

Promises and async/await fix this. Node.js style callbacks are "error-first": (err, result) => {}.

requestAnimationFrame(fn) runs fn before the next screen repaint. It is the right tool for animations.

A promise is an object for a value that is not ready yet. It is in one of three states: pending, fulfilled (success) or rejected (failure). Once settled, it never changes again.

const wait = (ms) => new Promise((resolve, reject) => {
  if (ms < 0) reject(new Error('negative time'));
  else setTimeout(() => resolve('done'), ms);
});

wait(500)
  .then(value => value + '!')      // return a value: next .then gets it
  .then(v => console.log(v))       // 'done!'
  .catch(err => console.error(err))// catches any error above
  .finally(() => console.log('always runs'));

Chaining rules

  • .then always returns a new promise.
  • Return a value and the next step receives it. Return a promise and the chain waits for it.
  • Throw an error (or return a rejected promise) and the chain skips to the next .catch.
  • After a .catch handles the error, the chain continues as success.
Common mistakeForgetting to return inside .then. The next step then gets undefined and does not wait for your inner promise.

Running many promises

MethodResult
Promise.all([...])Array of all results. Rejects as soon as one fails.
Promise.allSettled([...])Waits for all. Gives {status, value | reason} for each. Never rejects.
Promise.race([...])The first one to settle, success or failure.
Promise.any([...])The first one to succeed. Rejects with AggregateError only if all fail.
const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]); // runs in parallel

async/await is a cleaner way to write promise code. It looks like normal step-by-step code.

async function loadUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const user = await res.json();
    return user;                 // the async function returns a promise of user
  } catch (err) {
    console.error('failed', err);
    throw err;                   // or return a fallback
  } finally {
    hideSpinner();
  }
}

Rules to remember

  • An async function always returns a promise.
  • await pauses only that function. The rest of the program keeps running. The code after await runs as a microtask.
  • Use try/catch for errors. Or add .catch() when you call it.
  • await works only inside async functions and at the top level of ES modules.

Slow: one after another. Fast: together.

// Sequential: total time = a + b
const a = await getA();
const b = await getB();

// Parallel: total time = the slower of the two
const [a2, b2] = await Promise.all([getA(), getB()]);

await in loops

for (const id of ids) {
  await save(id);              // works: one by one, in order
}
ids.forEach(async (id) => {
  await save(id);              // does NOT wait: forEach ignores the promises
});
await Promise.all(ids.map(save)); // all at once
Say in interviewfetch only rejects on network errors. A 404 or 500 is still a fulfilled promise, so check res.ok.

The DOM (Document Object Model) is the page as a tree of objects. JavaScript reads and changes the page through it.

Select, create, change

const btn = document.querySelector('#save');        // first match (CSS selector)
const items = document.querySelectorAll('.item');   // all matches (NodeList)
const li = document.createElement('li');
li.textContent = 'New item';            // safe: plain text
li.classList.add('active');
li.dataset.id = '7';                    // data-id="7"
list.append(li);
li.remove();
SecurityNever put user input into innerHTML. It can run scripts (XSS attack). Use textContent.

Events

btn.addEventListener('click', (event) => {
  console.log(event.target, event.currentTarget);
});
btn.addEventListener('click', handler, { once: true });
btn.removeEventListener('click', handler);  // needs the same function reference
  • event.target is the element that was actually clicked.
  • event.currentTarget is the element that has the listener.
  • event.preventDefault() stops the browser's default action (form submit, link follow).
  • event.stopPropagation() stops the event from moving to other elements.

Bubbling and capturing

An event travels in three steps: capture (from the top down to the target), target, then bubble (back up). Listeners run in the bubble step by default. Pass { capture: true } to listen during capture.

Event delegation

Put one listener on the parent instead of many on the children. It uses less memory and works for items added later.

list.addEventListener('click', (e) => {
  const item = e.target.closest('li');
  if (!item || !list.contains(item)) return;
  console.log('clicked', item.dataset.id);
});

Loading scripts

  • <script defer> downloads while HTML is parsed, runs after parsing, keeps order.
  • <script async> runs as soon as it is downloaded, order is not guaranteed.
  • <script type="module"> is deferred by default.
  • DOMContentLoaded fires when HTML is parsed. load fires after images and styles too.

The browser gives you tools to call servers and save data. You must know how they behave.

fetch

const res = await fetch('/api/todos', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'Learn JS' })
});
if (!res.ok) throw new Error(`HTTP ${res.status}`); // 404 and 500 do NOT reject by themselves
const data = await res.json();

// cancel a request
const ctrl = new AbortController();
fetch(url, { signal: ctrl.signal });
ctrl.abort();

Where to store data in the browser

localStoragesessionStorageCookiesIndexedDB
Lives untilYou delete itTab is closedExpiry dateYou delete it
SizeAbout 5 MBAbout 5 MBAbout 4 KBLarge
Sent to serverNoNoYes, with every requestNo
StyleSync, strings onlySync, strings onlyStringsAsync, objects
localStorage.setItem('user', JSON.stringify({ name: 'Sara' }));
const user = JSON.parse(localStorage.getItem('user') ?? 'null');

Do not store passwords or tokens in localStorage. Any script on the page can read it. Login cookies should be HttpOnly, Secure and SameSite.

Same-origin policy and CORS

By default a page can only read responses from its own origin (same protocol, domain and port). CORS is how a server says "this other origin is allowed" with the header Access-Control-Allow-Origin. For some requests the browser first sends a preflight OPTIONS request to ask permission. The browser enforces CORS, not the server. The fix is on the server, not in your front-end code.

Modules let you split code into files. Each file has its own scope, and you choose what to share.

// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }  // named exports
export default function multiply(a, b) { return a * b; } // one default per file

// app.js
import multiply, { PI, add as sum } from './math.js';
import * as math from './math.js';
const mod = await import('./heavy.js');   // dynamic import, loads when needed
<script type="module" src="app.js"></script>
ES Modules (ESM)CommonJS (Node.js)
Syntaximport / exportrequire() / module.exports
LoadingStatic, analysed before running (tree shaking possible)Dynamic, at run time
Imports areLive read-only views of the exportCopies of the value
Top-level awaitYesNo

Modules run once. Importing the same file again gives the same instance. They are always in strict mode.

An iterable is anything you can loop with for...of: arrays, strings, Map, Set. It has a method named [Symbol.iterator] that returns an iterator with a next() method.

const it = [10, 20][Symbol.iterator]();
it.next(); // { value: 10, done: false }
it.next(); // { value: 20, done: false }
it.next(); // { value: undefined, done: true }

const range = {
  from: 1, to: 3,
  [Symbol.iterator]() {
    let n = this.from, end = this.to;
    return { next: () => n <= end ? { value: n++, done: false } : { done: true } };
  }
};
[...range];   // [1, 2, 3]

Generators

A generator function (function*) can pause at yield and continue later. It builds iterators for you and creates values lazily, only when asked.

function* idMaker() {
  let id = 1;
  while (true) yield id++;     // infinite, but only runs when asked
}
const ids = idMaker();
ids.next().value; // 1
ids.next().value; // 2

for await (const x of asyncIterable) loops over async data, such as streamed pages from an API.

Good developers expect things to fail and handle it well.

try {
  JSON.parse('{bad}');
} catch (err) {
  console.log(err.name, err.message);  // SyntaxError ...
} finally {
  console.log('cleanup');              // always runs
}

throw new Error('Something broke');    // throw Error objects, not strings

class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}
try { throw new ValidationError('Bad email', 'email'); }
catch (e) { if (e instanceof ValidationError) console.log(e.field); else throw e; }
ErrorTypical reason
ReferenceErrorVariable does not exist or is in the TDZ
TypeErrorWrong type, like calling undefined() or reading a property of null
SyntaxErrorCode or JSON is not valid
RangeErrorValue out of range, or too much recursion

Good to know

  • try/catch catches errors thrown inside it, including awaited promises. It does not catch errors inside a plain setTimeout callback or a promise you forgot to await.
  • A rejected promise with no .catch gives an unhandledrejection event.
  • Debug with console.log, console.table, console.error, the debugger statement, and breakpoints in DevTools.

These small functions show up in interviews all the time. They are built with closures and higher-order functions.

Debounce

Wait until the user stops doing something. Good for search boxes and resize.

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}
input.addEventListener('input', debounce(search, 300));

Throttle

Run at most once per interval, even if the event fires a lot. Good for scroll.

function throttle(fn, limit) {
  let waiting = false;
  return function (...args) {
    if (waiting) return;
    fn.apply(this, args);
    waiting = true;
    setTimeout(() => (waiting = false), limit);
  };
}

Memoize

Save results so the same input is not computed twice.

function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}
const slowSquare = n => n * n;
const fastSquare = memoize(slowSquare);

Currying and composition

const add = a => b => c => a + b + c;   // curried: one argument at a time
add(1)(2)(3);                           // 6

const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const pipe    = (...fns) => x => fns.reduce((v, f) => f(v), x);
pipe(n => n + 1, n => n * 2)(3);  // 8

You do not free memory by hand in JavaScript. The garbage collector does it. You still need to know when it cannot.

Garbage collection

Modern engines use mark and sweep. They start from "roots" (global variables, the current stack) and mark everything that can be reached. Anything not reachable is removed. Counting references is not the method, because two objects pointing at each other would never be freed.

Common memory leaks

  • Accidental globals (assigning to an undeclared variable).
  • setInterval or event listeners you never remove.
  • Closures that hold big objects for a long time.
  • Removed DOM elements that your code still points to.
  • Caches that grow forever. Use WeakMap or set a size limit.

Easy performance wins

  • Use event delegation instead of many listeners.
  • Debounce or throttle noisy events.
  • Change the DOM in batches. Many separate changes cause many layout recalculations (reflow).
  • Use requestAnimationFrame for animations.
  • Move heavy work to a Web Worker so the page stays responsive.
  • Load code only when needed with dynamic import().
All guides