JavaScriptBrowser And Performanceintermediate

JavaScript Browser APIs and Performance Interview Questions

The practical browser questions asked in front-end rounds — debounce and throttle, storage, lazy loading, tree shaking, Web Workers, service workers, CORS and avoiding reflows.

Published
TL;DR – Quick Answer

Browser and performance interviews ask how you keep a page fast and correct: debouncing and throttling, choosing between localStorage, sessionStorage and cookies, lazy loading and code splitting, tree shaking, Web Workers and service workers, CORS, and avoiding reflows. Expect to write debounce from memory and to explain at least one trade-off.

On This Page

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 debounce from memory is one of the most common live-coding tasks. Practise explaining why the closure keeps timer between 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) and Secure flags. 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 HttpOnly cookie 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?
Debounce waits until calls stop for a set time and then runs once — ideal for search boxes and resize-end logic. Throttle runs at most once per interval while calls keep coming — ideal for scroll position, drag and mouse-move handlers.
How do you measure JavaScript performance?
Use the Performance panel in Chrome DevTools to record a session and find long tasks, Lighthouse for page-level scores, and performance.now() or the Performance API for timing specific code. Always measure before and after a change.
Where should I store an authentication token in the browser?
An HttpOnly, Secure cookie is the safer default because JavaScript cannot read it, which protects it from XSS. localStorage is readable by any script on the page. Whichever you choose, also protect against CSRF and keep tokens short-lived.
What is code splitting?
Code splitting breaks one large JavaScript bundle into smaller chunks that load on demand, usually with dynamic import(). Users download only the code needed for the current page, which makes the first load faster.
When should I use a Web Worker?
Use a Web Worker for CPU-heavy work that would freeze the page — parsing large files, image processing, complex calculations. Workers cannot touch the DOM, so they suit pure computation that sends a result back with postMessage.
What are Core Web Vitals?
Google's main user-experience metrics: Largest Contentful Paint (loading speed), Interaction to Next Paint (responsiveness) and Cumulative Layout Shift (visual stability). JavaScript affects all three, especially INP when long tasks block the main thread.

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

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 28 November 2026 LinkedIn
Chat with us