JS Optimization techniques?

Optimising JavaScript means shipping less code, doing less work on the main thread, avoiding unnecessary DOM and rendering work, and using efficient data structures and algorithms, always guided by measurement rather than guesses.

1. Ship less JavaScript

  • Code splitting and lazy loading; tree shaking; remove unused dependencies.
  • Prefer platform features (native <dialog>, CSS animations, Intl) over libraries.
  • Move logic to the server (React Server Components, server rendering).

2. Keep the main thread free

  • Break long tasks (over 50 ms) into chunks and yield (setTimeout, scheduler.yield() where supported).
  • Move heavy computation to Web Workers.
  • Debounce and throttle high-frequency events; use passive listeners for scroll and touch.

3. Render efficiently

  • Batch DOM reads and writes to avoid layout thrashing.
  • Use requestAnimationFrame for visual updates; animate transform and opacity.
  • Virtualise long lists (render only visible rows).
  • Event delegation instead of thousands of listeners.
  • In React: avoid unnecessary re-renders (memoisation, stable props, the React Compiler), and keep state close to where it is used.

4. Algorithms and data structures

  • Map/Set for O(1) lookups instead of repeated array.find/includes.
  • Avoid nested loops over large data; precompute indexes.
  • Memoise expensive pure functions.

5. Network and caching

Cache responses, deduplicate requests, prefetch likely next steps, compress assets, and use HTTP caching and CDNs.

Measure first

Use the Performance panel, Lighthouse, Core Web Vitals (LCP, INP, CLS) from real users, and performance.mark/measure around suspect code. Optimise the hot path you measured, not the one you guessed.

Code example

js
1// Measure before optimising
2performance.mark("start");
3
4// 1. O(n*m) lookups -> O(n) with a Map
5const users = Array.from({ length: 20_000 }, (_, i) => ({ id: i, name: `user${i}` }));
6const orders = Array.from({ length: 20_000 }, (_, i) => ({ id: i, userId: (i * 7) % 20_000 }));
7
8let t = performance.now();
9const slow = orders.slice(0, 2_000).map((o) => users.find((u) => u.id === o.userId).name); // nested scan
10const slowMs = performance.now() - t;
11
12t = performance.now();
13const byId = new Map(users.map((u) => [u.id, u])); // index once
14const fast = orders.slice(0, 2_000).map((o) => byId.get(o.userId).name);
15const fastMs = performance.now() - t;
16console.log(`same result: ${slow.join() === fast.join()}, Map faster: ${fastMs < slowMs}`); // same result: true, Map faster: true
17
18// 2. Break a long task into chunks so the page stays responsive
19async function processInChunks(items, work, chunkMs = 8) {
20 let i = 0;
21 while (i < items.length) {
22 const end = performance.now() + chunkMs;
23 while (i < items.length && performance.now() < end) work(items[i++]);
24 await new Promise((r) => setTimeout(r, 0)); // yield to input and rendering
25 }
26}
27let total = 0;
28await processInChunks(Array.from({ length: 200_000 }, (_, i) => i), (n) => (total += n));
29console.log(total); // 19999900000
30
31// 3. Memoise an expensive pure function
32const cache = new Map();
33const slugify = (s) => cache.get(s) ?? (cache.set(s, s.toLowerCase().replace(/\W+/g, "-")), cache.get(s));
34console.log(slugify("Hello World"), cache.size); // hello-world 1
35
36performance.mark("end");
37console.log(`whole example took ${performance.measure("example", "start", "end").duration.toFixed(0)}ms`);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app