Interview preparation

JavaScript Interview Questions

Answers written to be said out loud in an interview — each with a common follow-up question and a link to the tutorial that explains it in depth.

Beginner
10
Intermediate
15
Experienced
8
01What are the differences between var, let and const?Beginner

var is function-scoped and hoisted with the value undefined. let and const are block-scoped and are in the temporal dead zone until declared. const cannot be reassigned, although objects it refers to can still be mutated.

Learn more: JavaScript — Variables: var, let, const
02What does typeof [] return and how do you check for an array?Beginner

"object", because arrays are objects. Use Array.isArray(value).

JavaScript Illustrative
typeof [];          // "object"
Array.isArray([]);  // true
Learn more: JavaScript — Data Types
03What is the difference between == and ===?Beginner

=== compares value and type without conversion. == converts types first, which leads to surprises like 0 == "" being true. Use === by default.

JavaScript Illustrative
0 == ''     // true
0 === ''    // false
null == undefined   // true
null === undefined  // false
Learn more: JavaScript — Operators
04What is hoisting?Beginner

Declarations are processed before code runs. Function declarations are fully hoisted; var is hoisted and initialised to undefined; let, const and class are hoisted but stay in the temporal dead zone until their declaration line.

Learn more: JavaScript — Hoisting
05What are truthy and falsy values?Beginner

Falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Everything else — including "0", [] and {} — is truthy.

Learn more: JavaScript — Type Conversion
06What are the primitive data types in JavaScript?Beginner

string, number, bigint, boolean, undefined, symbol and null. Primitives are immutable and compared by value. Everything else — objects, arrays, functions, dates — is an object, compared by reference.

Learn more: JavaScript — Data Types
07null vs undefined?Beginner

undefined means a value was never assigned: a declared variable, a missing property or argument, a function with no return. null is an intentional “no value” that you assign yourself. null == undefined is true, but null === undefined is false.

Learn more: JavaScript — Data Types
08Function declaration vs function expression?Beginner

A declaration (function add() {}) is hoisted completely, so it can be called before it appears in the code. A function expression (const add = function () {}) or arrow function is only available after the assignment line runs.

Learn more: JavaScript — Functions
09How do map, filter and reduce differ?Beginner

map transforms each item and returns a new array of the same length. filter keeps the items whose callback returns true. reduce folds the array into a single value — a total, an object, a grouped map. None of them changes the original array.

JavaScript Illustrative
const prices = [10, 25, 40];
prices.map(p => p * 2);              // [20, 50, 80]
prices.filter(p => p > 20);          // [25, 40]
prices.reduce((sum, p) => sum + p, 0); // 75
Learn more: JavaScript — Array Methods
10How do you copy an object, and what is a shallow copy?Beginner

Spread ({ ...obj }) or Object.assign creates a shallow copy: top-level properties are copied, but nested objects are still shared. structuredClone(obj) makes a deep copy of plain data (not functions or class instances).

Learn more: JavaScript — Objects
11What is a closure? Give a practical use.Intermediate

A closure is a function bundled with references to the variables in the scope where it was created, which stay alive after that scope ends. Uses include private state (counters, caches), function factories, and debounce/throttle utilities.

Learn more: JavaScript — Closures
12What is event delegation?Intermediate

Attaching one listener to a parent element and using event.target (with closest()) to handle events from its children. It relies on bubbling, reduces listeners, and automatically handles children added later.

Learn more: JavaScript — Event Delegation
13Why does await inside forEach not wait?Intermediate

forEach calls the async callback and ignores the promise it returns. Use for…of for sequential awaits or Promise.all(items.map(fn)) for parallel work.

Learn more: JavaScript — Async and Await
14How does the this keyword work?Intermediate

In a regular function, this depends on how the function is called: the object before the dot, the new object with new, undefined in strict-mode plain calls, or a value set by call/apply/bind. Arrow functions do not have their own this — they use the surrounding one.

Learn more: JavaScript — this Keyword
15Explain call, apply and bind.Intermediate

call and apply invoke a function immediately with a chosen this — call takes arguments individually, apply takes an array. bind returns a new function permanently bound to a this (and optional arguments).

Learn more: JavaScript — Call, Apply, and Bind
16What is prototypal inheritance?Intermediate

Every object has an internal link to a prototype object. When a property is not found on the object, JavaScript looks up the prototype chain. class syntax is built on this mechanism.

Learn more: JavaScript — Prototypes
17Debouncing vs throttling?Intermediate

Debouncing waits until events stop for a set time before running (good for search-as-you-type). Throttling runs at most once per interval while events continue (good for scroll or resize handlers).

Learn more: JavaScript — Debouncing and Throttling
18localStorage vs sessionStorage vs cookies?Intermediate

localStorage persists until cleared; sessionStorage lasts for the tab session; both are ~5 MB, JavaScript-only and never sent to the server. Cookies are small, can be httpOnly and are sent with every request — suitable for sessions.

Learn more: JavaScript — Local Storage
19What is the temporal dead zone?Intermediate

The time between entering a block and the line where a let or const variable is declared. The binding exists (it is hoisted) but reading it throws a ReferenceError, which catches bugs that var would hide by returning undefined.

Learn more: JavaScript — Hoisting
20What is the difference between event bubbling and capturing?Intermediate

An event travels down from window to the target (capture phase) and then back up (bubble phase). Listeners run in the bubble phase by default; pass { capture: true } to run during capture. stopPropagation() stops the journey.

Learn more: JavaScript — Event Bubbling
21Promise.all vs allSettled vs race vs any?Intermediate

all resolves with every result or rejects on the first failure. allSettled always resolves with each outcome. race settles with whichever promise settles first. any resolves with the first success and rejects only when all fail.

Learn more: JavaScript — Promises
22How do you handle errors with async/await?Intermediate

Wrap awaits in try/catch, or attach .catch() to the returned promise. An unhandled rejection in an async function is not caught by an outer try unless you await it. Remember that fetch only rejects on network failure — check response.ok for HTTP errors.

Learn more: JavaScript — Async and Await
23Why does fetch not reject on a 404 or 500?Intermediate

fetch resolves as soon as it receives a response, whatever its status. The request technically succeeded. Check response.ok (status 200–299) and throw yourself, and parse the body with await response.json().

Learn more: JavaScript — Fetch API
24What are ES modules and how are they different from scripts?Intermediate

Files that use import and export. They run in strict mode, have their own top-level scope, are deferred by default in the browser and are evaluated once even if imported many times. Imports are live, read-only bindings.

Learn more: JavaScript — ES Modules
25How do JavaScript classes relate to prototypes?Intermediate

class is syntax over prototypal inheritance. Methods are placed on Class.prototype, extends sets up the prototype chain, and super calls the parent. Classes add private fields (#x), static blocks and enforce new.

Learn more: JavaScript — Classes
26In what order do synchronous code, promise callbacks and setTimeout callbacks run?Experienced

Synchronous code runs first. Then the microtask queue (promise then/catch, queueMicrotask) is drained completely. Then one macrotask (such as a setTimeout callback) runs, followed again by all microtasks.

JavaScript Illustrative
setTimeout(() => console.log('timeout'));
Promise.resolve().then(() => console.log('promise'));
console.log('sync');
// sync, promise, timeout
Learn more: JavaScript — Promises
27How do you prevent XSS in JavaScript applications?Experienced

Never insert untrusted strings with innerHTML; use textContent or a framework that escapes output. Sanitise any HTML you must render, set a Content Security Policy, and keep tokens in httpOnly cookies.

Learn more: JavaScript — Security Best Practices
28What causes memory leaks in JavaScript?Experienced

Forgotten timers and event listeners, detached DOM nodes still referenced in code, growing global caches and closures that capture large objects. Use cleanup functions, WeakMap for caches and DevTools heap snapshots to diagnose.

Learn more: JavaScript — Memory Management Basics
29What are generators and when would you use one?Experienced

Generator functions (function*) can pause with yield and resume later, producing values lazily. They are useful for custom iterators, infinite sequences and processing large data in chunks.

Learn more: JavaScript — Iterators and Generators
30Map vs object, Set vs array — when do you use them?Experienced

Use Map for dynamic key–value collections: keys can be any type, it keeps insertion order, has size and is faster for frequent adds and deletes. Use Set for unique values and fast has() checks. Plain objects suit fixed, known shapes and JSON.

Learn more: JavaScript — Map and Set
31How do you find and fix slow JavaScript in the browser?Experienced

Profile with the Performance panel, look for long tasks over 50ms and layout thrashing. Fix by batching DOM reads and writes, debouncing handlers, virtualising long lists, moving heavy work to a Web Worker and splitting bundles.

Learn more: JavaScript — JavaScript Performance
32What does "use strict" change?Experienced

Assigning to undeclared variables throws instead of creating globals, this is undefined in plain function calls, duplicate parameter names are errors and some silent failures throw. Modules and classes are always strict.

Learn more: JavaScript — this Keyword
33What is the difference between microtasks and macrotasks?Experienced

Microtasks (promise reactions, queueMicrotask, MutationObserver) run right after the current script, and the whole queue is drained before anything else. Macrotasks (timers, I/O, UI events) run one per loop turn, with rendering possible between them.

Learn more: JavaScript — Promises