Skip to main content

Mid JavaScript Interview Questions

Curated Mid-level JavaScript interview questions for developers targeting mid positions. 20 questions available.

Last updated:

JavaScript Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of JavaScript interview questions and answers. This page contains expertly curated interview questions covering all aspects of JavaScript, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our JavaScript interview questions are designed to help you:

  • Understand core concepts and best practices in JavaScript
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next JavaScript interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic JavaScript concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

20 questions
Q1:

What are Web APIs in JavaScript?

Mid

Answer

Web APIs provide browser-based functionalities accessible to JavaScript.

Examples include:

  • DOM API
  • Fetch API
  • Web Storage
  • WebSockets
  • Canvas API
  • Service Workers

They enable dynamic, interactive, and offline-capable web applications.

Quick Summary: Web APIs are browser-provided APIs available in JavaScript: setTimeout, fetch, DOM API, localStorage, Geolocation, WebSockets, Canvas, etc. They run outside the JS engine (in C++ browser code), allowing async operations. When they complete, they push callbacks to the event queue. The JS engine itself has no I/O — Web APIs provide it.
Q2:

Explain the Fetch API and its advantages over XMLHttpRequest.

Mid

Answer

The Fetch API is promise-based and easier to work with than XMLHttpRequest.

  • Simpler syntax and chaining
  • Returns Response objects
  • Better error handling
  • Supports streaming and CORS
Quick Summary: Fetch API is Promise-based — no callback hell. Built-in JSON parsing: fetch(url).then(r => r.json()). Supports request/response streams, AbortController for cancellation, and headers control. XHR had verbose event handlers, required manual JSON parsing, and had no Promise support. Fetch is simpler, more powerful, and the modern standard.
Q3:

What are Service Workers and why are they important?

Mid

Answer

Service workers run in the background, independent of web pages.

  • Enable offline support
  • Implement caching strategies
  • Handle push notifications
  • Provide background sync

They form the foundation of Progressive Web Apps (PWAs).

Quick Summary: Service Workers are background scripts that run separately from the main page — they can intercept network requests, cache responses, and enable offline functionality. They're the foundation of Progressive Web Apps (PWAs). They run only over HTTPS, have no DOM access, and persist between sessions. Cache-first or network-first strategies control offline behavior.
Q4:

Explain WebSockets and their use cases.

Mid

Answer

WebSockets provide full-duplex communication over a single TCP connection.

Use cases include:

  • Real-time chat
  • Live stock updates
  • Gaming
  • Live dashboards
Quick Summary: WebSockets provide a persistent, full-duplex TCP connection between client and server. Unlike HTTP (request-response), WebSocket allows the server to push data to the client anytime. Use cases: real-time chat, live dashboards, multiplayer games, collaborative editing. socket.onmessage handles incoming messages; socket.send() sends outgoing ones.
Q5:

Difference between localStorage, sessionStorage, and IndexedDB.

Mid

Answer

  • localStorage: Persistent key-value storage.
  • sessionStorage: Data persists for session only.
  • IndexedDB: Client-side NoSQL database for structured data.
Quick Summary: localStorage: persists indefinitely across sessions, ~5-10MB, synchronous. sessionStorage: same API, but cleared when the tab closes, ~5MB. Cookies: ~4KB, sent with every HTTP request (useful for auth), can expire. IndexedDB: async, large storage (hundreds of MB), supports structured data and transactions — for complex offline apps and caching.
Q6:

Explain requestAnimationFrame and its importance.

Mid

Answer

requestAnimationFrame syncs animations with browser repaint cycles.

Improves smoothness and reduces CPU usage compared to timers.

Quick Summary: requestAnimationFrame(callback) schedules the callback to run just before the browser repaints — synchronized with the display refresh rate (typically 60fps = every 16ms). Animations updated via rAF are smooth because they're frame-synchronized. setTimeout/setInterval aren't frame-synchronized and can cause janky animations if they fire at the wrong time.
Q7:

How to improve DOM performance?

Mid

Answer

  • Minimize reflows and repaints
  • Use document fragments
  • Batch DOM updates
  • Cache selectors
  • Avoid layout thrashing
Quick Summary: DOM performance tips: batch reads before writes (avoid interleaved read/write causing layout thrashing), use DocumentFragment for bulk DOM insertions, minimize reflows (changing layout properties), use classList instead of style, virtual DOM libraries batch updates, use requestAnimationFrame for visual changes, and debounce scroll/resize handlers.
Q8:

What is Debouncing and Throttling?

Mid

Answer

Debouncing: Trigger function after a delay of inactivity.

Throttling: Trigger function at fixed intervals.

Useful for scroll, resize, and search inputs.

Quick Summary: Debouncing: delay execution until after a quiet period — a search input only fires after the user stops typing for 300ms. Throttling: execute at most once per time interval — a scroll handler fires at most every 100ms. Debouncing collapses bursts into one call at the end; throttling limits the rate. Both prevent performance-killing event handler spam.
Q9:

Explain memory leaks in JavaScript and how to avoid them.

Mid

Answer

Memory leaks occur when unused objects remain referenced.

  • Dangling references
  • Uncleared timers
  • Unremoved event listeners
  • Closures holding unnecessary data

Remove listeners, clear intervals, and nullify unused references.

Quick Summary: Memory leak sources: global variables accumulating data, event listeners added without removal (document.addEventListener used with dead references), closures accidentally holding large objects, timers (setInterval) never cleared, and detached DOM nodes held by JS variables. Fix: remove listeners when done, clear intervals, don't store large objects in globals.
Q10:

Difference between synchronous and asynchronous APIs.

Mid

Answer

Synchronous: Execution blocks until complete.

Asynchronous: Returns immediately, uses callbacks or promises.

Quick Summary: Synchronous APIs block until complete — good for simple scripts, terrible for UI. Asynchronous APIs return immediately and notify via callback/Promise/event when done — essential for anything that takes time (network, file, timers). Web APIs (fetch, setTimeout, DOM events) are always async. Node.js fs.readFileSync vs fs.readFile exemplifies the difference.
Q11:

What are design patterns in JavaScript?

Mid

Answer

Design patterns are reusable solutions to common problems.

  • Module
  • Singleton
  • Observer
  • Factory
  • MVC
Quick Summary: Common JS design patterns: Module (encapsulate with closures/IIFE), Observer (event-driven callbacks), Singleton (one global instance), Factory (create objects without new), Strategy (swap algorithms at runtime), Decorator (add behavior to objects dynamically), Command (encapsulate actions as objects). Patterns solve recurring design problems with proven solutions.
Q12:

Explain the Module Pattern.

Mid

Answer

Module pattern encapsulates private variables using closures.

Exposes only public methods, preventing namespace pollution.

Quick Summary: Module Pattern uses a closure (often IIFE) to create private state and expose only selected methods. const counter = (function() { let count = 0; return { increment() { count++ }, get() { return count } } })() — count is private, increment and get are public. Before ES6 modules, this was the standard encapsulation technique.
Q13:

Explain the Observer Pattern.

Mid

Answer

The observer pattern allows objects to subscribe to changes in another object.

Useful for events, data binding, and reactive programming.

Quick Summary: Observer Pattern: an object (subject) maintains a list of subscribers (observers) and notifies them when its state changes. Events in the browser ARE the Observer pattern — addEventListener is subscribe, dispatchEvent is notify. Custom implementation: EventEmitter with on(), emit(), and off(). Enables decoupled, reactive systems.
Q14:

Difference between Singleton and Factory Patterns.

Mid

Answer

Singleton: Only one instance allowed.

Factory: Creates objects without exposing creation logic.

Quick Summary: Singleton: only one instance ever created — a shared DB connection, a config object. class Config { static instance; static getInstance() { if (!this.instance) this.instance = new Config(); return this.instance; } }. Factory: creates objects without exposing constructor logic — function createUser(role) returns different user objects based on role. Factory is more flexible; Singleton is for shared global state.
Q15:

What is lazy loading in JavaScript?

Mid

Answer

Lazy loading delays loading non-critical resources until needed.

Used for images, scripts, and modules to improve load time.

Quick Summary: Lazy loading defers loading resources until they're needed. Images: or IntersectionObserver to load when entering the viewport. JS modules: import() — const { fn } = await import("./module") loads the module on demand instead of at startup. Reduces initial load time significantly for large apps.
Q16:

Explain async iterators and for-await-of.

Mid

Answer

Async iterators allow iteration over asynchronous data streams.

for-await-of simplifies consuming async sequences.

Quick Summary: Async iterators yield Promises instead of plain values. for await...of loops consume them: for await (const chunk of readableStream) { process(chunk); }. Used with streams, paginated APIs, or any async data source that produces values over time. Define with Symbol.asyncIterator. Native Node.js streams implement async iteration.
Q17:

Explain Web Workers.

Mid

Answer

Web Workers run scripts in background threads.

Prevent blocking the main UI thread during heavy computations.

Quick Summary: Web Workers run JavaScript in a background thread — no DOM access, but full JS execution. They communicate with the main thread via postMessage(). Use them for CPU-intensive tasks (image processing, data compression, complex calculations) that would freeze the UI if run on the main thread. Workers are separate OS threads, not the event loop.
Q18:

How is security handled in JavaScript on the client side?

Mid

Answer

  • Sanitize inputs to prevent XSS
  • Use HTTPS
  • Implement CSP
  • Prevent CSRF
Quick Summary: Client-side JS security: never trust user input (validate server-side), avoid innerHTML with untrusted content (XSS risk), use Content Security Policy (CSP) headers to block inline scripts, store tokens in httpOnly cookies (not localStorage), sanitize DOM content, and avoid eval() or Function() with dynamic strings.
Q19:

Difference between event capturing and bubbling.

Mid

Answer

Capturing: Event flows parent ? child.

Bubbling: Event flows child ? parent.

Quick Summary: Capturing phase: event travels from window down to the target. Bubbling phase: event travels from the target back up to window. addEventListener(type, handler) defaults to bubbling. addEventListener(type, handler, true) uses capturing. stopPropagation() stops further propagation in either phase. Most UI code uses bubbling; capturing is useful for intercepting events before they reach their target.
Q20:

How do you optimize JavaScript performance?

Mid

Answer

  • Minimize DOM operations
  • Use event delegation
  • Apply lazy loading
  • Debounce/throttle events
  • Prevent memory leaks
  • Split code into modules
Quick Summary: JS performance tips: minimize DOM reads/writes (batch them), use event delegation instead of per-element listeners, debounce/throttle event handlers, avoid memory leaks (clean up listeners and intervals), use Web Workers for CPU work, lazy-load modules and images, avoid blocking the main thread, and use requestAnimationFrame for animations.

Curated Sets for JavaScript

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice