Web Fundamentals · Lesson 4 of 10 · 4 min
JavaScript Performance & Bundle Optimization
This is where you show you can build a fast app, not just a working one. You'll be asked to explain runtime bottlenecks, memory leaks, and how you'd shrink a 2MB bundle.
Master the Event Loop
JavaScript is single-threaded. The Event Loop is what keeps the UI from freezing by managing an execution queue. If you block the main thread with a long-running synchronous task, the browser can't repaint, respond to clicks, or do anything else.
The key is understanding task priority. The loop services the Call Stack first. When the stack is empty, it runs all available microtasks (Promise callbacks, queueMicrotask). Only after the microtask queue is empty does it process one macrotask (like setTimeout, setInterval, I/O, or rendering).
The interview question: You will be given a snippet with
console.logstatements inside asetTimeout(..., 0), aPromise.resolve().then(...), and the main body. You must predict the exact output order. The answer is always: synchronous code first, then promises (microtasks), thensetTimeout(macrotask).
Control Execution with Debounce and Throttle
For frequently firing events like scroll, resize, or input, you can't run a heavy function on every single event. It will cripple performance. You control the rate of execution with debouncing or throttling.
- Debounce: Executes the function only after a period of inactivity. Good for search inputs; you only fire the API call when the user stops typing.
- Throttle: Executes the function at most once every X milliseconds. Good for scroll-based animations or tracking mouse position.
You will likely be asked to implement one of these from scratch. Here is a solid debounce implementation.
function debounce<T extends (...args: any[]) => void>(
func: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const context = this;
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
// Usage:
// const debouncedSearch = debounce(api.search, 300);
// searchInput.addEventListener('input', (e) => debouncedSearch(e.target.value));
The trap: A naive implementation forgets to handle this and arguments. Using an arrow function for the returned function will break this context. Using func.apply(context, args) preserves it.
Hunt Down Memory Leaks
A memory leak is memory that is allocated but never released, causing your app's footprint to grow over time until it becomes sluggish or crashes. SPAs are especially vulnerable.
Garbage collection is automatic, but it can only clean up what is unreachable. Leaks happen when you unintentionally keep references to objects that are no longer needed.
Common culprits are "zombie" references from subscriptions or event listeners. If you add an event listener to a global object (like window or document) from within a component that later gets unmounted, that listener's callback will keep the component's scope alive unless you explicitly remove it.
The same applies to timers (setInterval) and WebSocket connections. Always clean them up in the component's lifecycle "destroy" or "unmount" phase (e.g., the return function in a useEffect hook).
To sound like you've actually done this, mention your tool: "I'd start by using the Chrome DevTools Memory tab. I'd take a heap snapshot, perform some actions in the app, take another snapshot, and compare them to find detached DOM nodes or objects that haven't been garbage collected."
Shrink Your Bundle for Faster Loads
The biggest factor for initial page load performance is often the size of your JavaScript bundle. A user on a slow mobile connection isn't going to wait for your 2MB main.js to download and parse. The goal is to send the absolute minimum code required to render the initial view.
Tree Shaking is the first step. Modern bundlers like Webpack or Rollup use ES module import/export syntax to statically analyze your code and remove any exports that you never use. If you import { a } from './utils' but never use a, it won't be in the final bundle. This works best with libraries that are authored with tree-shaking in mind.
Code Splitting is the most impactful technique. Instead of one giant bundle, you break your app into smaller chunks. The initial chunk contains only the code for the first-page view. Then, you load other chunks on demand.
The standard mechanism for this is the dynamic import() syntax.
button.addEventListener('click', async () => {
// This tells the bundler to create a separate chunk for 'heavy-module.js'
const { doComplexThing } = await import('./heavy-module.js');
doComplexThing();
});
This is most commonly done at the route level. When a user navigates from the home page to the /dashboard, you dynamically import the dashboard's code. This is a core feature of frameworks like Next.js and is essential for any non-trivial SPA.
Try it
Open the network tab in your browser's dev tools and filter by "JS". Load a large web app like Figma, Spotify, or the AWS console. Navigate around. Watch the new .js chunks being loaded as you interact with different features. Identify which user action triggered the download.
Next: Image, Video, and Media Optimization Strategies.
Lock it in — apply this lesson under interview conditions.