Master JavaScript interview questions covering closures, prototypes, event loop, async/await, DOM manipulation, ES6+ features, design patterns, performance optimization, and testing best practices.

Fundamentals15 topics

beginner

var vs let vs const

How the three declaration keywords differ in scope, hoisting behavior, and mutability.

scopehoistinges6
beginner

Hoisting Explained

Why function and variable declarations appear to be 'moved' to the top of their scope before code runs.

hoistingscopefundamentals
beginner

Type Coercion and Equality

How JavaScript automatically converts values between types, and why == and === behave differently.

equalitycoercionfundamentals
beginner

Primitive vs Reference Types

The distinction between value types (numbers, strings, booleans) and reference types (objects, arrays, functions), and how it affects copying and comparison.

typesmemoryfundamentals
intermediate

The Event Loop and Call Stack

How JavaScript's single-threaded call stack cooperates with the event loop, task queue, and microtask queue to handle asynchronous work.

event-loopasyncfundamentals
beginner

Lexical Scope and Scope Chain

How JavaScript resolves variable names based on where code is physically written, not where it is called from.

scopeclosuresfundamentals
beginner

Truthy and Falsy Values

The short, memorizable list of values JavaScript treats as false in a boolean context, and everything else.

conditionalscoercionfundamentals
beginner

Template Literals and Tagged Templates

Backtick strings that support multi-line text and expression interpolation, plus the tagged template function pattern.

stringses6syntax
beginner

Operator Precedence and Short-Circuit Evaluation

How JavaScript decides the order to evaluate operators, and how && / || can skip evaluating part of an expression entirely.

operatorssyntaxfundamentals
beginner

typeof and instanceof Operators

Two different tools for checking a value's type at runtime — one for primitives, one for constructor-based checks on objects.

typesoperatorsfundamentals
beginner

NaN and Number Edge Cases

Understanding NaN's self-inequality, floating-point precision issues, and safe ways to check for numeric validity.

numbersedge-casesfundamentals
beginner

Switch Statements and Fall-Through

How switch statements compare values with strict equality and why forgetting break causes cases to 'fall through.'

control-flowsyntaxfundamentals
beginner

Immediately Invoked Function Expressions Basics

A function that runs the instant it's defined, historically used to create private scope before block-scoping and modules existed.

closuresscopepatterns
beginner

Strict Mode Explained

The opt-in stricter variant of JavaScript that catches silent errors, disables risky features, and is the default inside ES modules and classes.

fundamentalsbest-practicessyntax
intermediate

Symbol and BigInt Primitives

Two newer primitive types: Symbol for guaranteed-unique property keys, and BigInt for integers beyond Number's safe range.

es6typesadvanced

Functions12 topics

intermediate

Closures Explained

How an inner function retains access to variables from its enclosing scope even after that outer function has finished executing.

closuresscopefunctions
intermediate

Higher-Order Functions

Functions that take other functions as arguments, return functions, or both — the foundation of functional-style JavaScript.

functional-programmingarray-methodsfunctions
beginner

Callbacks and Callback Hell

Passing a function to be executed later, and why deeply nested callbacks became a maintainability problem promises and async/await later solved.

asynccallbacksfunctions
beginner

Arrow Functions vs Regular Functions

Syntax differences aside, arrow functions differ from regular functions in how they bind this, whether they can be constructors, and whether they have their own arguments object.

arrow-functionsthisfunctions
beginner

The arguments Object and Rest Parameters

The array-like arguments object available in regular functions, and the modern rest parameter syntax that replaces most of its use cases.

functionses6syntax
advanced

Function Currying and Partial Application

Transforming a multi-argument function into a sequence of single-argument functions, and pre-filling some arguments ahead of time.

functional-programmingclosuresadvanced
intermediate

Function.prototype.call, apply, and bind

Three methods for explicitly controlling what this refers to inside a function, with different argument-passing conventions.

thisfunctionsadvanced
beginner

Default Parameters

How to give function parameters fallback values that are used automatically when no argument or undefined is passed.

functionses6syntax
intermediate

Pure Functions and Side Effects

Functions that always return the same output for the same input and don't modify anything outside themselves, versus functions that mutate state or perform I/O.

functional-programmingbest-practicestesting
beginner

Function Hoisting and Declaration vs Expression

How function declarations, function expressions, and named function expressions differ in hoisting behavior and use cases.

hoistingfunctionsfundamentals
intermediate

Recursion and Stack Depth

Writing functions that call themselves to solve problems by breaking them into smaller subproblems, and the call-stack limits that come with it.

algorithmsrecursionadvanced
intermediate

Method Chaining and Fluent Interfaces

Designing functions/methods that return the calling object (usually this) so multiple calls can be strung together in one expression.

patternsapi-designfunctions

Async12 topics

intermediate

Promises Fundamentals

The Promise object representing an eventual result of an asynchronous operation, with its three states and chaining behavior.

promisesasynces6
intermediate

Async/Await Syntax

Syntactic sugar over Promises that lets asynchronous code read like synchronous code, using async functions and the await keyword.

asyncpromisessyntax
advanced

Promise.all, allSettled, race, and any

Four static Promise combinators for running multiple promises concurrently, each with different rules for how they settle.

promisesconcurrencyadvanced
advanced

Microtasks vs Macrotasks

The two distinct queues the event loop draws from, and why microtasks always run before the next macrotask.

event-loopasyncadvanced
intermediate

The Fetch API

The modern, Promise-based browser API for making HTTP requests, replacing XMLHttpRequest for most use cases.

fetchhttpasync
intermediate

Error Handling in Async Code

Strategies for catching and handling errors across callbacks, promise chains, and async/await, including unhandled rejections.

error-handlingasyncbest-practices
beginner

setTimeout, setInterval, and Timer Precision

Scheduling delayed or repeating code execution, and why the delay argument is a minimum, not a guarantee.

timersasyncevent-loop
advanced

Async Iterators and for-await-of

Iterating over sequences of values that arrive asynchronously, such as paginated APIs or streamed data, using async generators and for-await-of.

generatorsasyncadvanced
intermediate

Debouncing and Throttling

Two techniques for limiting how often a function runs in response to rapidly repeating events, like scrolling or typing.

performanceeventsasync
intermediate

Promise Chaining Pitfalls

Common mistakes when chaining .then() calls, including forgetting to return, nested chains, and swallowed errors.

promisesdebuggingbest-practices
advanced

Node.js Event Loop Phases

How Node.js's libuv-based event loop differs from the browser's, with distinct phases for timers, I/O callbacks, and microtasks.

nodejsevent-loopadvanced
intermediate

Web Storage vs Cookies for Async Data

How localStorage, sessionStorage, and cookies differ in capacity, lifetime, and how they interact with server requests, relevant when caching async fetch results client-side.

storagesecuritybrowser-apis

Objects12 topics

intermediate

Prototype Chain Explained

How objects inherit properties and methods from other objects through an internal link called the prototype, forming a chain up to Object.prototype.

prototypesinheritanceoop
intermediate

The this Keyword in Depth

How the value of this is determined dynamically at call time based on four binding rules, rather than lexically like a normal variable.

thisfunctionsadvanced
intermediate

ES6 Classes and Inheritance

The class syntax as syntactic sugar over prototype-based inheritance, including extends, super, and static members.

classesinheritanceoop
beginner

Object Destructuring

Extracting properties from objects into individual variables using a concise pattern-matching syntax, including renaming, defaults, and nested patterns.

destructuringes6syntax
intermediate

Object.freeze, seal, and Immutability Patterns

Built-in methods for restricting how much an object can be changed, and why true deep immutability requires more than a single call.

immutabilityobjectsbest-practices
intermediate

Getters and Setters

Defining object properties backed by functions that run on access or assignment, letting you compute values or add validation transparently.

objectsencapsulationclasses
beginner

Optional Chaining and Nullish Coalescing

Two ES2020 operators for safely accessing deeply nested properties and providing fallback values only for null/undefined.

es6syntaxobjects
beginner

Object.keys, values, entries, and Iteration

The three static methods for extracting an object's own enumerable properties as arrays, and how they interact with for...in and destructuring.

objectsiterationes6
intermediate

Shallow Copy vs Deep Copy

The difference between copying only an object's top level versus recursively copying every nested structure, and the tools available for each.

objectsimmutabilitybest-practices
intermediate

Map and Set vs Plain Objects and Arrays

The dedicated key-value and unique-value collection types, and why they're often better choices than objects and arrays for certain use cases.

data-structureses6objects
advanced

Composition Over Inheritance

Building complex objects by combining small, focused behaviors together rather than through deep class inheritance hierarchies.

design-patternsoopadvanced
intermediate

Private Class Fields and Encapsulation

The # syntax for true private fields and methods in JavaScript classes, enforced by the engine rather than by convention.

classesencapsulationes6

DOM10 topics

beginner

DOM Manipulation Basics

Selecting, creating, modifying, and removing elements from the live document tree using core DOM APIs.

dombrowser-apisfundamentals
intermediate

Event Bubbling and Capturing

The two phases an event travels through the DOM tree — capturing down from the root, then bubbling back up from the target — and how to hook into either.

eventsdomfundamentals
intermediate

Event Delegation Pattern

Attaching a single event listener to a common ancestor instead of many listeners on individual children, relying on event bubbling.

eventsdomperformance
beginner

preventDefault vs stopPropagation

Two distinct event methods often confused: one cancels the browser's default action for an event, the other stops the event from traveling further through the DOM.

eventsdomfundamentals
intermediate

localStorage, sessionStorage, and IndexedDB

The three main client-side storage APIs, ranging from simple synchronous key-value storage to a full asynchronous, transactional database in the browser.

storagebrowser-apisperformance
intermediate

The Virtual DOM Concept

The in-memory representation of the UI that frameworks like React diff against the previous version to compute minimal real DOM updates.

domperformanceframeworks
advanced

MutationObserver and Reacting to DOM Changes

A browser API for observing and reacting to changes in the DOM tree — added/removed nodes, attribute changes, text changes — asynchronously and efficiently.

dombrowser-apisadvanced
advanced

Web Components and Custom Elements

Native browser APIs for creating reusable, encapsulated HTML elements without relying on a JavaScript framework.

web-componentsdomadvanced
intermediate

Intersection Observer for Lazy Loading

An efficient, asynchronous browser API for detecting when an element enters or exits the viewport, commonly used for lazy loading and infinite scroll.

performancebrowser-apisdom
advanced

Shadow DOM and Style Encapsulation

A native browser mechanism for attaching an isolated DOM subtree to an element, preventing styles and markup from leaking in either direction.

web-componentscssadvanced

ES6+12 topics

beginner

ES Modules: import and export

The native, standardized module system for splitting JavaScript code across files, replacing older ad-hoc patterns like CommonJS and IIFEs for the browser.

moduleses6syntax
advanced

Iterators and the Iterable Protocol

The formal protocol that makes an object usable with for...of, spread syntax, and destructuring, and how to implement it on custom objects.

iteratorses6advanced
advanced

Generator Functions

Functions that can pause and resume execution using yield, producing values lazily one at a time and automatically implementing the iterator protocol.

generatorses6advanced
beginner

Spread and Rest Operators

The three-dot syntax that expands an iterable into individual elements (spread) or collects multiple elements into a single array (rest), depending on context.

es6syntaxarrays
beginner

Array Destructuring

Unpacking values from arrays into individual variables by position, including skipping elements, defaults, and swapping variables.

destructuringes6syntax
advanced

Proxy and Reflect

Meta-programming APIs that let you intercept and customize fundamental object operations like property access, assignment, and deletion.

metaprogrammingadvancedes6
advanced

Well-Known Symbols and Symbol.iterator

The set of built-in Symbol values that let user code hook into and customize core language behaviors like iteration, type coercion, and instanceof checks.

symbolsmetaprogrammingadvanced
beginner

Array.prototype Methods: flat, flatMap, includes

Three newer array methods that flatten nested arrays, combine mapping with flattening in one pass, and check for element presence without coercion quirks.

arrayses6fundamentals
advanced

Tagged Template Literals for Safe HTML

Using tagged template functions to automatically escape interpolated values, a real-world defense against injection when building HTML or SQL strings dynamically.

securityes6advanced
intermediate

Optional Catch Binding and Error Cause

Two smaller but useful ES additions: catching an error without naming a variable, and chaining errors together with a structured cause property.

error-handlinges6syntax
beginner

Numeric Separators and New Number Methods

Underscore separators for readable large numeric literals, plus static Number methods that avoid relying on global functions with looser coercion.

numberses6fundamentals
beginner

Array.from and Array-Like Objects

Converting iterables and array-like objects (things with a length and indices but no array methods) into real arrays, optionally with a mapping function.

arrayses6fundamentals

Patterns10 topics

intermediate

Module Pattern and Revealing Module Pattern

Using closures (often via an IIFE) to create private state and expose only a deliberately chosen public API.

design-patternsclosuresencapsulation
intermediate

Singleton Pattern

Ensuring only one instance of a particular object or resource ever exists throughout an application's lifetime, with a single global access point.

design-patternssingletonarchitecture
intermediate

Factory Pattern

Using a function or method to create and return objects, encapsulating the object-creation logic away from the calling code.

design-patternsfactoryarchitecture
intermediate

Observer Pattern and Pub/Sub

A pattern where one or more 'observers' subscribe to notifications from a 'subject,' decoupling the code that triggers events from the code that reacts to them.

design-patternsobserverevents
intermediate

Debounced Search Pattern (Practical Application)

A common, composed real-world pattern combining debouncing, async fetch cancellation, and race-condition handling for a search-as-you-type UI.

design-patternsasyncperformance
intermediate

Strategy Pattern

Encapsulating interchangeable algorithms or behaviors behind a common interface so they can be swapped at runtime without changing the code that uses them.

design-patternsstrategyfunctions
advanced

Decorator Pattern in JavaScript

Wrapping a function or object to add extra behavior transparently, without modifying its original source code.

design-patternsdecoratoradvanced
advanced

State Machine Pattern for UI Logic

Modeling a component's behavior as a finite set of distinct states and explicit transitions between them, instead of scattered boolean flags.

design-patternsstate-managementarchitecture
advanced

Dependency Injection in JavaScript

Passing a component's dependencies in from outside rather than having it construct or reach out for them internally, improving testability and flexibility.

design-patternstestingarchitecture
intermediate

Immutable Update Patterns for State Management

Conventions for updating nested objects and arrays without mutating the original, central to predictable state management in frameworks like Redux and React.

design-patternsimmutabilitystate-management

Performance8 topics

intermediate

Memory Management and Garbage Collection

How JavaScript automatically allocates and reclaims memory, and the mark-and-sweep algorithm that decides what can be safely freed.

memoryperformanceadvanced
advanced

Reflow, Repaint, and Layout Thrashing

The two expensive rendering steps triggered by DOM/style changes, and the anti-pattern of alternating reads and writes that forces the browser to recalculate layout repeatedly.

performancedomadvanced
advanced

Web Workers for Offloading Heavy Computation

Running JavaScript on a separate background thread to keep the main thread responsive during CPU-intensive work.

web-workersperformanceadvanced
intermediate

requestAnimationFrame and Smooth Animations

A browser API for scheduling visual updates in sync with the display's refresh cycle, producing smoother animations than setTimeout-based approaches.

performanceanimationbrowser-apis
intermediate

Code Splitting and Lazy Loading Modules

Breaking a JavaScript bundle into smaller chunks loaded on demand, using dynamic import() to reduce the initial page load's JavaScript payload.

performancebundlinges6
intermediate

Memoization and Caching Strategies

Storing the results of expensive function calls keyed by their arguments, so repeated calls with the same input can return a cached result instantly.

performanceoptimizationfunctions
intermediate

Passive Event Listeners and Scroll Performance

The passive option for addEventListener that tells the browser a handler won't call preventDefault, letting scrolling proceed immediately without waiting.

performanceeventsbrowser-apis
advanced

Bundle Size Optimization and Tree Shaking

Techniques bundlers use to eliminate unused code from a final JavaScript bundle, relying heavily on ES modules' static import/export structure.

performancebundlinges6

Testing9 topics

beginner

Unit Testing Fundamentals with Jest

The core building blocks of writing unit tests — test/describe blocks, assertions with expect, and the arrange-act-assert structure — using Jest as the representative framework.

testingjestfundamentals
intermediate

Mocking Functions and Modules

Replacing real dependencies with controlled fake implementations during tests to isolate the code under test and verify how it interacts with its dependencies.

testingmockingjest
intermediate

Test-Driven Development (TDD)

A development workflow where a failing test is written before the implementation code, following a strict red-green-refactor cycle.

testingtddbest-practices
beginner

Debugging with the Browser DevTools Debugger

Using breakpoints, the call stack panel, and watch expressions in browser DevTools to pause execution and inspect program state at a specific point.

debuggingdevtoolsfundamentals
intermediate

Snapshot Testing

Capturing a serialized representation of a value or rendered output and comparing future test runs against that saved baseline, flagging any unexpected differences.

testingjestbest-practices
intermediate

Testing Asynchronous Code

Techniques and common pitfalls for correctly testing promise-based and callback-based asynchronous code, including fake timers.

testingasyncjest
intermediate

Code Coverage and Its Limitations

What code coverage metrics actually measure (lines/branches executed by tests), and why high coverage numbers don't guarantee genuinely good tests.

testingcode-coveragebest-practices
intermediate

Integration Testing vs Unit Testing

The distinction between testing units in isolation with mocked dependencies versus testing how multiple real components work together, and the tradeoffs of each.

testingintegration-testingarchitecture
advanced

End-to-End Testing with Playwright/Cypress

Automated browser tests that simulate real user interactions through an actual, full application stack, providing the highest-confidence but slowest and most expensive layer of the testing pyramid.

testinge2eadvanced