Writing JavaScript that works is the first half of a front-end job; keeping the page fast is the second. This guide covers the eight browser and performance questions interviewers ask most — debouncing, storage, lazy loading, tree shaking, Web Workers, service workers, CORS and reflows.
Why interviewers ask about browser APIs and performance
Slow pages lose users, and many slow pages are caused by JavaScript: handlers that fire hundreds of times a second, bundles full of unused code, heavy work on the main thread, layouts recalculated in a loop. Interviewers ask these questions to see whether you notice those problems and know the standard fixes.
These questions are especially common for candidates with some experience, where "how would you make this faster?" replaces "what does this keyword do?".
How to answer these questions
Name the problem, the fix and how you would measure it. "The search fired a request on every keystroke, so I debounced it to 300 ms and checked the network panel" is a complete, convincing answer.
Several answers here build on asynchronous JavaScript — timers, promises and dynamic import() — covered in the promises and async/await guide.
Q1. What are debouncing and throttling?
Debouncing runs a function only after calls have stopped for a set time — ideal for search inputs. Throttling runs it at most once per interval — ideal for scroll and resize handlers.
// Debounce
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// Throttle
function throttle(fn, limit) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= limit) { last = now; fn(...args); }
};
}
Interview note: Writing
debouncefrom memory is one of the most common live-coding tasks. Practise explaining why the closure keepstimerbetween calls.
Q2. What is the difference between localStorage, sessionStorage and cookies?
localStorage persists until it is cleared (about 5 MB), sessionStorage lasts only for the browser tab (about 5 MB), and cookies are small (about 4 KB), can expire, and are sent to the server with every request.
localStorage— no expiry, same origin only. Good for user preferences.sessionStorage— cleared when the tab closes. Good for tab-specific state.- Cookies — support
HttpOnly(no JavaScript access) andSecureflags. Good for session tokens.
Interview note: Trap: "is it safe to keep a JWT in localStorage?" Any script on the page can read localStorage, so an XSS bug exposes the token. An
HttpOnlycookie cannot be read by JavaScript.
Q3. What is lazy loading and how is it implemented in JavaScript?
Lazy loading delays loading a resource until it is actually needed, which speeds up the first page load. Use loading="lazy" for images, dynamic import() for code splitting, and IntersectionObserver to load content when it enters the viewport.
// Dynamic import (code splitting)
const btn = document.getElementById("load");
btn.addEventListener("click", async () => {
const { Chart } = await import("./Chart.js");
new Chart(document.getElementById("canvas"));
});
// IntersectionObserver lazy image
const io = new IntersectionObserver((entries) => {
entries.forEach(e => {
if (e.isIntersecting) { e.target.src = e.target.dataset.src; }
});
});
Q4. What is tree shaking?
Tree shaking is dead-code elimination done by bundlers such as Webpack, Rollup and Vite. They analyse static ES module import/export statements and drop exports that are never imported.
// math.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b; // never imported
// app.js
import { add } from "./math.js";
// After tree shaking, multiply is removed from the bundle
Tree shaking only works with static ES module syntax — not with require().
Q5. What are Web Workers?
Web Workers run JavaScript on a background thread, separate from the main UI thread, so heavy computation does not freeze the page.
// main.js
const worker = new Worker("worker.js");
worker.postMessage({ data: [1, 2, 3, 4, 5] });
worker.onmessage = (e) => console.log("Result:", e.data);
// worker.js
self.onmessage = (e) => {
const result = e.data.data.reduce((a, b) => a + b, 0);
self.postMessage(result);
};
Workers cannot touch the DOM; they communicate with the page only through postMessage.
Q6. What are service workers and how do they enable PWAs?
A service worker is a script the browser runs in the background, separate from the page. It can intercept network requests, which enables offline support, background sync and push notifications — the core of a Progressive Web App.
// Register
navigator.serviceWorker.register("/sw.js");
// sw.js — serve from cache, fall back to the network
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request)
.then(cached => cached || fetch(event.request))
);
});
Q7. What is CORS and why does the browser block some requests?
CORS (Cross-Origin Resource Sharing) is the browser rule that lets a server say which other origins may read its responses. A page can read a response from another origin only if that server sends headers such as Access-Control-Allow-Origin.
An origin is the scheme, host and port together, so http://localhost:3000 and http://localhost:8080 are different origins. For requests with custom headers, JSON bodies or methods such as PUT, the browser first sends an OPTIONS preflight request to ask permission.
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Interview note: Trap: "can you fix a CORS error in front-end code?" No — the server must send the headers, or you route the call through your own backend or a dev proxy. CORS is enforced by the browser, which is why the same request works in Postman.
Q8. What are reflow and repaint, and how do you avoid unnecessary ones?
A reflow (layout) recalculates the size and position of elements; a repaint redraws pixels without changing layout. Reflows are expensive, so batch DOM writes, avoid reading layout values between writes, and animate transform and opacity instead of top or width.
// Bad — read, write, read, write forces a layout on every iteration
items.forEach(el => {
el.style.width = box.offsetWidth + "px";
});
// Better — read once, then write
const w = box.offsetWidth;
items.forEach(el => { el.style.width = w + "px"; });
Reading offsetWidth, getBoundingClientRect() or scrollTop right after a style change forces the browser to lay out the page immediately — a problem known as layout thrashing.
How to prepare
Write debounce and throttle from memory, then wire debounce to a search input that calls a real API. Open DevTools and use the Performance and Network panels to confirm the improvement — interviewers love candidates who measure.
Finish with advanced JavaScript for memory leaks and garbage collection, the other half of keeping an app healthy.
Frequently Asked Questions
What is the difference between debounce and throttle?
How do you measure JavaScript performance?
Where should I store an authentication token in the browser?
What is code splitting?
When should I use a Web Worker?
What are Core Web Vitals?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — Check the Java Full Stack training details

