JavaScript Performance Optimization
Published by Brayan K
Performance optimization in JavaScript is the practice of making code run faster and feel more responsive by reducing wasted work, minimizing costly DOM updates, managing memory carefully, and avoiding blocking the main thread.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Choose a user-visible question before changing code
“Faster” may mean an earlier first result, shorter total work, fewer bytes downloaded or a page that responds while work continues. These goals can conflict. Write down the action, data size, device conditions and correctness contract before choosing an optimization. A small loop benchmark cannot establish the responsiveness of an entire page.
function prepareAll(values) {
const trace = [];
const ready = values.map(value => { trace.push("prepare " + value); return value * 2; });
trace.push("publish " + ready[0]);
return trace;
}
function prepareFirst(values) {
const trace = [];
const first = values[0] * 2;
trace.push("prepare " + values[0], "publish " + first);
const remaining = values.slice(1).map(value => { trace.push("prepare " + value); return value * 2; });
// The remaining results are ready for a later application update.
void remaining;
return trace;
}
// This trace records application order, not measured milliseconds.
console.log(prepareAll([1, 2, 3]).join(" | "));
console.log(prepareFirst([1, 2, 3]).join(" | "));
// ✅ Expected output:
// prepare 1 | prepare 2 | prepare 3 | publish 2
// prepare 1 | publish 2 | prepare 2 | prepare 3The second workflow publishes earlier in its own sequence; the trace does not prove an earlier browser paint. Rendering needs an opportunity after JavaScript yields, and later work can still block interaction. Performance Optimization owns work counts and algorithm contracts. This lesson focuses on scheduling, workload boundaries and verifying an optimization in context.
Async syntax does not move CPU work off the main thread
const trace = [];
async function work() {
for (let i = 0; i < 3; i++) trace.push("item " + i);
await Promise.resolve();
trace.push("continued");
}
const pending = work();
trace.push("caller");
await pending;
console.log(trace.join(","));
// ✅ Expected output:
// item 0,item 1,item 2,caller,continuedThe loop still runs in the caller’s thread. Declaring async does not create a worker. An already-resolved promise schedules a microtask continuation, which is not a reliable opportunity for the browser to process input or paint. Event Loop, Microtasks & Async Internals owns task and microtask ordering.
const trace = [];
let finish;
const done = new Promise(resolve => { finish = resolve; });
setTimeout(() => { trace.push("task"); finish(); }, 0);
for (let i = 0; i < 3; i++) {
await Promise.resolve();
trace.push("micro " + i);
}
await done;
console.log(trace.join(","));
// ✅ Expected output:
// micro 0,micro 1,micro 2,taskBreaking a long operation into smaller tasks can improve opportunities for interaction while adding scheduling overhead. There is no universal chunk size: one item may be much more expensive than another. A count limit bounds calls per chunk, not elapsed time. Avoid reporting invented frame counts or milliseconds from a controlled test.
Choose a real task boundary when responsiveness needs one
function yieldTask() {
return new Promise(resolve => {
const channel = new MessageChannel();
channel.port1.onmessage = () => {
channel.port1.close(); channel.port2.close(); resolve();
};
channel.port2.postMessage(null);
});
}
const trace = ["before"];
await yieldTask();
trace.push("after");
console.log(trace.join(","));
// ✅ Expected output:
// before,afterThe message delivery supplies a task boundary, and both ports are closed after use. It does not guarantee a paint between the two trace entries. Where supported, scheduler.yield provides a purpose-built scheduling API; choose and check a fallback for your supported browsers. A setTimeout callback can also yield a task, but its delay is a minimum scheduling request and may be clamped.
requestAnimationFrame coordinates work before a rendering update; doing heavy computation inside it can still delay that update. DOM Reflow, Repaint & Browser Rendering Pipeline owns read/write batching and geometry. Use a worker for suitable CPU work when off-thread execution is the requirement, while accounting for message transfer and worker startup.
A faster-looking result must not publish stale work
let generation = 0, visible = "";
function start() {
const own = ++generation;
return value => { if (own === generation) visible = value; };
}
const old = start(), recent = start();
recent("new result"); old("old result");
console.log(visible);
// ✅ Expected output:
// new resultCancellation and publication ownership solve different problems. A cancelled operation may already have performed work, and an operation that ignores its signal may finish later. Advanced Scope, Closures & Lexical Environments owns this generation pattern; Advanced Fetch API Patterns (Retry, Timeout, AbortController) owns cooperative cancellation.
const controller = new AbortController(), effects = [];
async function work() {
for (const item of [1, 2, 3]) {
controller.signal.throwIfAborted();
effects.push(item);
if (item === 1) controller.abort("stop");
await Promise.resolve();
}
}
try { await work(); }
catch (reason) { console.log(reason, effects.join(",")); }
// ✅ Expected output:
// stop 1Prefer pure per-item transformations when partial work should remain private until completion. An all-or-nothing return value does not roll back callbacks that already mutated external state. Make any intermediate UI explicit instead of displaying incomplete data as a complete result.
Reduce shipped and repeated work without hiding its cost
let creates = 0;
function createReport() { creates++; return value => "Report " + value; }
let report;
function showReport(value) {
report ??= createReport();
return report(value);
}
console.log(creates);
console.log(showReport("A"), showReport("B"), creates);
// ✅ Expected output:
// 0
// Report A Report B 1This fixture verifies deferred creation, not code splitting or download size. A real dynamic import may create a separate chunk in a bundler, but the build and network trace must establish that. Module Bundlers: Webpack, Parcel, Vite (Overview) owns build output. Deferring work trades startup cost for first-use cost; preserve loading and failure feedback.
Debouncing can reduce repeated handler calls while delaying a result; throttling can intentionally drop intermediate work. Debouncing & Throttling for Performance owns their exact contracts. A cache can improve repeated work only while its key, invalidation and lifetime remain correct; do not hide stale data behind a speed claim.
const items = [{ value: 1 }, { value: 2 }];
const snapshot = items.slice();
items.push({ value: 3 });
items[0].value = 9;
console.log(snapshot.length, snapshot[0].value);
// ✅ Expected output:
// 2 9Document whether a chunked job reads a snapshot or a live collection. A shallow copy stabilizes the array’s membership and order but retains references to its objects. Deep Copy vs Shallow Copy & Data Structures owns deeper copying; copying every object can itself be significant work.
Profile the complete interaction and repeat the comparison
Record a representative interaction in browser performance tools. Identify long scripting tasks, layout work and the point where the user receives feedback. Compare the same production build, data size and device conditions before and after the change; repeat runs and retain the trace rather than selecting the fastest result. Separate cold loading from warm-cache behavior.
Check correctness, cancellation, error feedback and keyboard interaction as part of that comparison. A lower microbenchmark time can accompany more memory retention, delayed first use or a broken user interaction. These examples make no measured timing claim; a real optimization recommendation requires a recorded application workload.
Guided exercise: yield only between unfinished batches
Use the literal hints to place checkpoints after each pair of items, but not after the final result. The injected checkpoint records scheduling decisions without promising browser paint.
const trace = [], values = [1, 2, 3, 4, 5];
for (let index = 0; index < values.length; index++) {
trace.push(values[index]);
if ((index + 1) % ___ === 0 && index + 1 < values.length) { // 👉 replace ___ with 2
await Promise.resolve();
trace.___("yield"); // 👉 replace ___ with push
}
}
console.log(trace.join(","));
// ✅ Expected output:
// 1,2,yield,3,4,yield,5Independent brief: cooperative mapping with explicit limits
Implement mapInChunks(items, transform, options). Require a dense array, a synchronous transform, a yieldControl function and an integer size from 1 through 1000. Snapshot array membership before the first yield. Process in order, pass each value and index to transform, and reject thenable results rather than silently turning this into an async-concurrency helper.
Check an optional AbortSignal before work, before each item and after each awaited yield. Yield only between nonfinal chunks. Return the complete result array; preserve errors and exact abort reasons. The supplied yieldControl determines the actual scheduling behavior. The fixture below controls it manually, so it proves chunk boundaries and cancellation without measuring responsiveness.
async function mapInChunks(items, transform, { size = 100, yieldControl, signal } = {}) {
if (!Array.isArray(items) || typeof transform !== "function" || typeof yieldControl !== "function")
throw new TypeError("items, transform and yieldControl are required");
if (!Number.isInteger(size) || size < 1 || size > 1000)
throw new RangeError("size must be an integer in 1..1000");
for (let index = 0; index < items.length; index++)
if (!Object.hasOwn(items, index)) throw new TypeError("items must be dense");
// Snapshot membership and order before the first yield; objects remain shared.
const source = items.slice(), result = [];
signal?.throwIfAborted();
for (let index = 0; index < source.length; index++) {
signal?.throwIfAborted();
const value = transform(source[index], index);
if (value !== null && (typeof value === "object" || typeof value === "function") &&
typeof value.then === "function")
throw new TypeError("transform must be synchronous");
result.push(value);
if ((index + 1) % size === 0 && index + 1 < source.length) {
await yieldControl();
signal?.throwIfAborted();
}
}
return result;
}
const visits = [], yields = [];
console.log((await mapInChunks([1, 2, 3, 4, 5], value => value * 2, {
size: 2, yieldControl: async () => { yields.push("yield"); }
})).join(","), yields.length);
const controller = new AbortController(), reason = { stop: true };
let release;
const pending = mapInChunks([1, 2, 3], value => { visits.push(value); return value; }, {
size: 2, signal: controller.signal,
yieldControl: () => new Promise(resolve => { release = resolve; })
});
console.log(visits.join(","));
controller.abort(reason); release();
try { await pending; }
catch (error) { console.log(error === reason, visits.join(",")); }
try { await mapInChunks([1], async value => value, { yieldControl: async () => {} }); }
catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// 2,4,6,8,10 2
// 1,2
// true 1,2
// TypeError transform must be synchronousReference notes
The long-task guidance explains why smaller tasks can leave opportunities for interaction. Validate changes with actual application traces; the deterministic policy tests here do not establish a speedup on a particular device.
Practice quiz
What does this complete program print? const trace=[];async function work(){trace.push("inside");await Promise.resolve();trace.push("after")}const pending=work();trace.push("caller");await pending;console.log(trace.join(","));
- inside,caller,after
- caller,inside,after
- inside,after,caller
- after,inside,caller
Answer: inside,caller,after. Async execution begins synchronously until suspension.
What does this complete program print? const values=[1,2,3,4,5];let yields=0;for(let i=0;i<values.length;i++)if((i+1)%2===0&&i+1<values.length)yields++;console.log(yields);
- 1
- 2
- 3
- 5
Answer: 2. Only the two nonfinal chunk boundaries request yields.
What does this complete program print? const a=[{n:1}];const b=a.slice();a[0].n=2;a.push({n:3});console.log(b.length,b[0].n);
- 2 2
- 1 1
- 1 2
- 2 1
Answer: 1 2. Membership is copied while the nested object remains shared.
What does this complete program print? const controller=new AbortController();const reason={stop:true};controller.abort(reason);try{controller.signal.throwIfAborted()}catch(value){console.log(value===reason)}
- false
- undefined
- TypeError
- true
Answer: true. AbortSignal retains the exact supplied reason.
What does this complete program print? let generation=0,value="";const begin=()=>{const own=++generation;return x=>{if(own===generation)value=x}};const a=begin(),b=begin();b("new");a("old");console.log(value);
- new
- old
- undefined
Answer: new. Only the current generation may publish.
What does this complete program print? let calls=0;const make=()=>{calls++;return x=>x};let fn;function use(x){fn??=make();return fn(x)}use(1);use(2);console.log(calls);
- 0
- 1
- 2
- undefined
Answer: 1. The lazy factory is called once across these uses.
What does this complete program print? const controller=new AbortController(),seen=[];try{for(const n of [1,2]){controller.signal.throwIfAborted();seen.push(n);controller.abort("stop")}}catch{}console.log(seen.join(","));
- 1,2
- 1
- 2
Answer: 1. Cancellation prevents later work but does not undo the first effect.
What does this complete program print? let calls=0;const items=[];for(let i=0;i<items.length;i++)calls++;console.log(calls);
- 1
- undefined
- TypeError
- 0
Answer: 0. An empty input has no per-item work or between-chunk yield.
Continue this course
- Previous: Working with WebSockets for Real-Time Features
- Next: Building Reusable UI Components with Pure JS — Create modular, accessible components without a framework
- Quick reference: JavaScript cheat sheet
Related lessons
- Performance Optimization
- Event Loop, Microtasks & Async Internals
- DOM Reflow, Repaint & Browser Rendering Pipeline
- Advanced Scope, Closures & Lexical Environments
- Advanced Fetch API Patterns (Retry, Timeout, AbortController)
- Module Bundlers: Webpack, Parcel, Vite (Overview)
- Debouncing & Throttling for Performance
- Deep Copy vs Shallow Copy & Data Structures