LearnFrenzy
Sign in Take a free test

JavaScript interview · Set 6 of 10

Web Performance and Security for JavaScript Developers

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Fast and safe by default

Performance answers start with measuring Core Web Vitals; security answers name the threat (XSS, CSRF) and the specific defence. Both show you think about real users.

  • SpeedLCP, INP, CLS and how to improve them.
  • MemoryLeaks, cleanup and heap snapshots.
  • SecurityXSS, CSRF, CORS and CSP.

Senior front-end interviews always include “how would you make this page faster?” and “how do you keep it secure?”. Strong answers start with measurement and name specific threats with specific defences.

1. What are Core Web Vitals?

Google's user-experience metrics, also used in search ranking: LCP (Largest Contentful Paint — loading, aim under 2.5 s), INP (Interaction to Next Paint — responsiveness, under 200 ms) and CLS (Cumulative Layout Shift — visual stability, under 0.1). Measure them with Lighthouse in the lab and real-user data from the field.


2. How do you make a slow page load faster?

Measure first, then: ship less JavaScript (code splitting, tree-shaking, removing heavy libraries), lazy-load below-the-fold images and components, optimise images (modern formats, correct sizes, srcset), preload the hero image and key fonts, cache static assets with long-lived hashed filenames, use a CDN, and render critical content on the server.

<img src="hero.webp" width="1200" height="630" fetchpriority="high" alt="Students in a mock interview">
<img src="card.webp" loading="lazy" decoding="async" width="400" height="260" alt="">
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>

3. How do you improve responsiveness (INP)?

Keep event handlers short: break long tasks into chunks and yield to the browser (await scheduler.yield() where supported, or setTimeout), move heavy work to Web Workers, debounce expensive input handlers, avoid layout thrashing, and render long lists virtually.


4. What causes memory leaks in front-end apps?

Listeners and timers that are never removed, detached DOM nodes still referenced from JavaScript, growing caches and global arrays, closures holding large objects, and subscriptions not cleaned up when components unmount. Find them with the browser's Memory panel — take heap snapshots before and after an action and compare.

function startPolling() {
  const id = setInterval(refresh, 5000);
  const onResize = () => layout();
  window.addEventListener('resize', onResize);
  return () => {                        // cleanup — call it when leaving the page/component
    clearInterval(id);
    window.removeEventListener('resize', onResize);
  };
}

5. What is XSS and how do you prevent it?

Cross-Site Scripting is when attacker-controlled input runs as script in your page — stealing sessions or acting as the user. Prevent it by escaping output (frameworks do this by default), avoiding innerHTML and eval with user data, sanitising any HTML you must render (DOMPurify), setting a strict Content Security Policy, and keeping session cookies HttpOnly.

// dangerous
comment.innerHTML = userInput;
// safe
comment.textContent = userInput;
// when HTML is genuinely needed
comment.innerHTML = DOMPurify.sanitize(userHtml);

6. What is CSRF and how do you prevent it?

Cross-Site Request Forgery tricks a logged-in user's browser into sending an unwanted request (for example, a hidden form that transfers money), because cookies are sent automatically. Defences: SameSite=Lax or Strict cookies, anti-CSRF tokens on state-changing requests, checking the Origin header, and never changing state with GET.


7. Explain CORS.

The browser's same-origin policy blocks scripts from reading responses from another origin. CORS lets a server opt in with headers such as Access-Control-Allow-Origin. Non-simple requests (custom headers, JSON POSTs) trigger a preflight OPTIONS request. CORS is enforced by browsers, not servers — it is not an authentication mechanism.

Access-Control-Allow-Origin: https://app.learnfrenzy.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true

8. What is a Content Security Policy?

An HTTP header telling the browser which sources of scripts, styles, images and connections are allowed. A strict CSP (no inline scripts, nonces or hashes for the ones you need) blocks most injected scripts even if an XSS bug slips through.

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; img-src 'self' https: data:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'

Remember

Key points

  • Measure before optimising

    Lighthouse plus real-user data.

  • Less JavaScript wins

    Split, lazy-load and remove.

  • Escape output

    Never put user input in innerHTML.

  • CORS is not auth

    Servers must still check permissions.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is tree-shaking? Basic

    Removing unused exports from the bundle at build time; it relies on static ES module imports.

  2. 2 How do you prevent layout shift from images and ads? Basic

    Always set width and height (or aspect-ratio) and reserve space for ads and embeds.

  3. 3 What is the difference between authentication and authorisation? Basic

    Authentication checks who you are; authorisation checks what you may do. Both must happen on the server.

  4. 4 Where should a front-end store an access token? Intermediate

    Prefer an HttpOnly, Secure, SameSite cookie set by the server; if a token must live in JavaScript, keep it in memory with short expiry and refresh through a secure cookie.

  5. 5 What is clickjacking? Intermediate

    Loading your site in a hidden iframe to trick users into clicking. Prevent it with frame-ancestors in CSP (or X-Frame-Options).

  6. 6 How does HTTP caching work for static files? Intermediate

    Serve files with content hashes in their names and Cache-Control: public, max-age=31536000, immutable; HTML stays short-lived so new deployments are picked up.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links