PrepStack › Frontend › JavaScript

JavaScript interview cheat sheet

Language core, async, browser and output puzzles

Almost every frontend (and many full-stack) interviews start here. Interviewers check that you know how the language actually behaves: types and coercion, scope and closures, this, prototypes, the event loop and promises. Then they ask you to write small utilities like debounce or a Promise.all polyfill, and to predict output. Read the 15-minute revision first, then switch to Quiz mode and answer out loud.

15-minute revision

  1. 8 types: 7 primitives (string number bigint boolean undefined null symbol) + object. typeof null === 'object' is a historic bug; use Array.isArray for arrays.
  2. === compares without coercion; == coerces first. Only null == undefined is a handy == case. NaN is never equal to itself, so use Number.isNaN or Object.is.
  3. Falsy values: false 0 -0 0n '' null undefined NaN. Everything else, including [], {} and '0', is truthy.
  4. var is function-scoped and hoisted as undefined. let/const are block-scoped and hoisted but sit in the TDZ until their line runs. const stops reassignment, not mutation.
  5. A closure is a function plus the variables it captured from where it was created. It is used for private state, once, memoization, debounce and module patterns.
  6. this is decided at call time: new > bind/call/apply > obj.method() > default (undefined in strict mode). Arrow functions have no own this; they use the enclosing one.
  7. Objects inherit through the prototype chain. class is syntax over prototypes; extends links Child.prototype to Parent.prototype.
  8. Spread and Object.assign copy shallowly. Use structuredClone for deep copies (it keeps Date, Map, Set and cycles, but not functions).
  9. Event loop: run all sync code, then empty every microtask (promise callbacks, await continuations, queueMicrotask), then take one macrotask (timer, I/O, event), and repeat.
  10. Promise.all fails fast; allSettled never rejects; race settles with the first to settle; any resolves with the first success (AggregateError if all fail).
  11. async functions always return a promise. await pauses only that function. Use Promise.all for parallel work, and remember that forEach does not wait for async callbacks.
  12. Events go through capture → target → bubble. Delegation means one listener on a parent plus e.target.closest(...).
  13. Debounce waits until the calls stop (search box). Throttle runs at most once per interval (scroll, resize).
  14. ESM (import/export) is static, async and live-bound, and allows tree-shaking. CommonJS (require) is dynamic, synchronous and copies values.
  15. Use Map for any key type, ordered entries and frequent adds and deletes. WeakMap uses object keys and does not stop garbage collection. Common memory leaks: forgotten listeners, timers, globals and detached DOM nodes.

Foundations

Data types & typeof

7 primitive types are copied by value, and objects are shared by reference.

  • Primitives: string, number, bigint, boolean, undefined, null, symbol. They are immutable, so string methods return new strings.
  • Everything else is an object: arrays, functions, dates, maps and class instances. Variables hold a reference to the object.
  • number is a 64-bit float. Integers are safe up to Number.MAX_SAFE_INTEGER (2^53 − 1). Use BigInt (10n) beyond that.
  • undefined means “not assigned yet”, while null means “intentionally empty”.
  • Primitives temporarily get wrapper objects when you call methods on them ('hi'.toUpperCase()).

Interview questions

  • What are the data types in JavaScript?
  • Difference between null and undefined?
  • Is JavaScript pass-by-value or pass-by-reference?
  • Why is 0.1 + 0.2 !== 0.3?

Type coercion & == vs ===

== converts types before comparing and === does not. Default to ===.

  • Implicit coercion happens with + (string wins), other math operators (convert to number), ==, and boolean contexts such as if and &&.
  • + with any string concatenates: 1 + '2' is '12'. -, * and / convert to numbers: '3' - 1 is 2.
  • Objects become primitives through Symbol.toPrimitive, then valueOf, then toString. That is why [] + {} is '[object Object]'.
  • == rules in short: null == undefined and nothing else is equal to them; otherwise both sides are usually converted to numbers.
  • Object.is(a, b) is like === except that NaN equals NaN and +0 does not equal -0.

Interview questions

  • Difference between == and ===?
  • What does [] == ![] return and why?
  • What is the difference between || and ???

var / let / const, scope & hoisting

Declarations are hoisted. var starts as undefined, while let/const throw until their line runs (the TDZ).

  • Scope decides where a variable is visible: global, function, block ({}) for let/const, and module scope.
  • JavaScript uses lexical (static) scope: where code is written decides what it can see, not where it is called from.
  • Hoisting: in the creation phase, declarations are registered before any code runs. Function declarations are hoisted with their body.
  • let/const are hoisted too but stay in the Temporal Dead Zone until their declaration executes, so accessing them throws ReferenceError.
  • A let in a for loop creates a new binding per iteration. That is why closures in the loop see 0, 1, 2 instead of 3, 3, 3.

Interview questions

  • What is hoisting?
  • What is the Temporal Dead Zone?
  • Why does a var loop with setTimeout print 3, 3, 3?
  • Can you change a const object?

Functions: declarations, arrows, IIFE & HOFs

Functions are values: you can store them, pass them in and return them. Arrow functions are short and have no own this.

  • Functions are first-class: assign them, pass them as arguments, return them and add properties to them.
  • A higher-order function takes or returns a function. Examples are map, filter, setTimeout and debounce.
  • Default parameters (b = 10), rest (...args) and spread (f(...arr)) replaced the old arguments object.
  • An IIFE (function(){ ... })() runs immediately and creates a private scope. It was the module pattern before ES modules.
  • A pure function returns the same output for the same input and has no side effects, which makes it easy to test and memoize.

Interview questions

  • What is a first-class function and a higher-order function?
  • Function declaration vs function expression?
  • When should you NOT use an arrow function?

Modern syntax: destructuring, spread, ?. and ??

Since ES6, JavaScript has short syntax for pulling values out, copying and safely reading data.

  • Destructuring pulls values out of objects and arrays, with defaults, renaming ({ a: alias }), nesting and rest (...others).
  • Spread ... copies arrays and objects (shallowly) or expands an iterable into arguments. Rest collects the remaining items into an array or object.
  • Optional chaining a?.b?.c and fn?.() stop and return undefined when the value on the left is null or undefined.
  • Nullish coalescing ?? gives a default only for null or undefined. Logical assignment operators: a ||= b, a &&= b, a ??= b.
  • Template literals support interpolation, multi-line strings and tagged templates (styled-components, String.raw).

Interview questions

  • Difference between spread and rest?
  • How do you swap two variables without a temp?
  • What does optional chaining return when the chain breaks?

Array & object methods

Use map, filter and reduce to transform data. Know which methods mutate the original.

  • map transforms every item, filter keeps some, and reduce folds everything into one value (sum, group-by, an object).
  • find/findIndex return the first match, some and every short-circuit, and includes uses SameValueZero (so it finds NaN).
  • sort() converts items to strings by default, so always pass a comparator for numbers: (a, b) => a - b.
  • Objects: Object.keys / values / entries / fromEntries, Object.assign, Object.freeze, hasOwn.
  • ES2023 added non-mutating copies: toSorted, toReversed, toSpliced and with(index, value).

Interview questions

  • Difference between map and forEach?
  • Difference between slice and splice?
  • How do you remove duplicates from an array?
  • Why does [1, 10, 2].sort() give [1, 10, 2]?

Core concepts

Closures

A function keeps access to the variables of the scope where it was created, even after that scope has finished.

  • Every function stores a hidden link to its lexical environment. When it runs later, it looks up variables through that chain.
  • The captured variables are live bindings, not copies. If the variable changes, the closure sees the new value.
  • Uses: data privacy (module pattern), factories, once, memoization, debounce/throttle, partial application, and React hooks' stale closures.
  • Each call to the outer function creates a new environment, so two counters do not share state.
  • Closures keep captured objects alive. Capturing big data in long-lived callbacks can cause memory leaks.

Interview questions

  • What is a closure? Give a real use case.
  • How would you create private variables in JavaScript?
  • Do closures copy variables?

this keyword, call / apply / bind

For normal functions, this depends on how the function is called. Arrow functions take it from the surrounding code.

  • Default binding: a plain call f() gives undefined in strict mode or modules, and globalThis in sloppy mode.
  • Implicit binding: obj.f() sets this to obj. Pulling the method out (const g = obj.f) loses it.
  • Explicit binding: f.call(ctx, a, b), f.apply(ctx, [a, b]), or f.bind(ctx), which returns a new permanently bound function.
  • new binding: new F() creates a fresh object and sets this to it.
  • Arrow functions ignore all of these rules and use the enclosing this. Class field arrows like tick = () => {} auto-bind to the instance.

Interview questions

  • Explain call, apply and bind.
  • What is this inside an arrow function?
  • Why does a method lose this when passed as a callback?

Prototypes, inheritance & classes

Objects delegate missing properties to their prototype. class is cleaner syntax over the same mechanism.

  • Every object has a hidden [[Prototype]] link. You read it with Object.getPrototypeOf(obj); __proto__ is legacy.
  • Property lookup walks the prototype chain until it finds the property or reaches null. Writes always go to the object itself.
  • Functions have a .prototype object. new F() creates an object whose [[Prototype]] is F.prototype.
  • class adds extends/super, static members, getters and setters, and #private fields. Class bodies are strict mode, and classes are not hoisted for use (TDZ).
  • Put methods on the prototype so all instances share one copy. Put data on the instance.

Interview questions

  • What is prototypal inheritance?
  • Difference between __proto__ and prototype?
  • What does the new keyword do?
  • Are JavaScript classes real classes?

Shallow vs deep copy & immutability

Spread and Object.assign copy one level. structuredClone copies deeply. freeze is shallow.

  • A shallow copy creates a new top-level object, but nested objects are still shared with the original.
  • A deep copy recursively copies nested objects so that changes do not leak back to the original.
  • JSON.parse(JSON.stringify(x)) is a quick deep copy but loses undefined, functions, Date (becomes a string), Map/Set, Infinity/NaN, and throws on cycles.
  • structuredClone(x) (in browsers and Node 17+) handles Date, Map, Set, RegExp, typed arrays and circular references. It throws for functions and DOM nodes, and drops class prototypes.
  • Object.freeze blocks adding, removing and changing properties one level deep. Object.seal allows changes but blocks adding and removing.

Interview questions

  • Shallow copy vs deep copy?
  • How do you deep clone an object?
  • Write a simple deep clone function.

Async JavaScript

Event loop: call stack, microtasks & macrotasks

Run the sync code, drain all microtasks, run one macrotask, and repeat. That is why promises beat setTimeout(0).

  • JavaScript runs on one thread with one call stack. Slow work (timers, network, I/O) is handed to the host (browser APIs or Node's libuv), which queues a callback when it is done.
  • Macrotasks (tasks): setTimeout, setInterval, I/O, UI events, MessageChannel, and in Node setImmediate.
  • Microtasks: promise then/catch/finally, code after await, queueMicrotask, MutationObserver. In Node, process.nextTick runs even before promise microtasks.
  • After each macrotask, the engine empties the whole microtask queue (including microtasks added meanwhile) before rendering or taking the next task.
  • Browsers may render (rAF, then style, layout and paint) between tasks. A long sync loop or endless microtasks freeze the UI.

Interview questions

  • Explain the event loop.
  • Microtask vs macrotask: which runs first?
  • Is JavaScript single-threaded? How does async work then?
  • What is process.nextTick vs setImmediate in Node?

Promises & combinators

A promise is a placeholder for a future value. It is pending, then fulfilled or rejected, and it settles only once.

  • States: pending → fulfilled | rejected. Once settled, the state never changes, and extra resolve/reject calls are ignored.
  • then always returns a new promise. Returning a value passes it down the chain, returning a promise waits for it, and throwing makes the next promise reject.
  • catch(fn) is then(undefined, fn) and recovers the chain unless it re-throws. finally gets no argument and passes the value through.
  • The executor new Promise((resolve, reject) => ...) runs synchronously. Only the callbacks are async.
  • Always handle rejections. An unhandled rejection logs a warning in browsers and crashes Node 15+ by default.

Interview questions

  • What is a promise and what are its states?
  • Promise.all vs allSettled vs race vs any?
  • What is callback hell and how do promises fix it?
  • Convert a callback API into a promise (promisify).

async / await & error handling

await pauses the async function, not the thread. Run independent awaits in parallel with Promise.all.

  • An async function always returns a promise. A return v resolves it and a throw rejects it.
  • await unwraps a promise. The rest of the function continues later as a microtask, and other code runs meanwhile.
  • Handle errors with try/catch/finally around awaits, or attach .catch to the returned promise.
  • Sequential vs parallel: await a(); await b(); takes the sum of both times. await Promise.all([a(), b()]) takes the max.
  • Top-level await works in ES modules (and Node .mjs). for await...of consumes async iterables (streams, paginated APIs).

Interview questions

  • How do async/await and promises relate?
  • How do you run multiple awaits in parallel?
  • Why doesn't forEach work with await?

Browser & modules

DOM events: bubbling, capturing & delegation

Events travel down (capture), hit the target, then bubble up. Listen once on a parent and use closest().

  • Three phases: capture (window → target), target, bubble (target → window). Listeners run in the bubble phase by default. Pass { capture: true } for the capture phase.
  • e.target is the element that was actually clicked. e.currentTarget is the element whose listener is running.
  • Event delegation: one listener on a container handles events for many (even future) children. It uses less memory and works for dynamic lists.
  • preventDefault() cancels the browser's default action (link navigation, form submit). stopPropagation() stops the event travelling further.
  • Listener options: { once: true } auto-removes the listener, { passive: true } promises no preventDefault (smooth scrolling), and { signal } removes it via AbortController.

Interview questions

  • What is event bubbling and capturing?
  • What is event delegation and why use it?
  • Difference between e.target and e.currentTarget?

Modules: ES Modules vs CommonJS

ESM (import/export) is the standard: static, async and tree-shakeable. CommonJS (require) is Node's older synchronous system.

  • ESM imports are resolved before the code runs (static), which enables tree-shaking. Imports are live read-only bindings to the exporter's variables.
  • CommonJS require() runs at call time (dynamic, synchronous) and returns a copy of module.exports at that moment.
  • ESM runs in strict mode, has top-level await, and its top-level this is undefined. CommonJS wraps each file in a function that provides require, module, exports and __dirname.
  • Node uses ESM when the file is .mjs or package.json has "type": "module". Otherwise .js is CommonJS. import() (dynamic import) works in both and returns a promise.
  • In browsers, <script type="module"> is deferred by default, runs once per URL, and follows CORS.

Interview questions

  • Difference between ES modules and CommonJS?
  • What is tree-shaking?
  • Named vs default exports?

Storage: localStorage, sessionStorage, cookies, IndexedDB

Use cookies for data the server needs on every request, Web Storage for small client-only strings, and IndexedDB for large or structured data.

  • localStorage persists until it is cleared. sessionStorage lasts for the tab's lifetime. Both are synchronous, store strings only, hold about 5 MB, and are scoped by origin.
  • Cookies are sent with every matching HTTP request (about 4 KB each). Their flags: HttpOnly (hidden from JavaScript), Secure (HTTPS only), SameSite=Lax/Strict/None (CSRF protection), Expires/Max-Age.
  • IndexedDB is an async, transactional, large-capacity store for objects and blobs, used by offline apps. Libraries such as idb or Dexie make it easier.
  • The storage event fires in other tabs when localStorage changes, which is handy for syncing logout across tabs.

Interview questions

  • localStorage vs sessionStorage vs cookies?
  • Where should you store a JWT on the client?

Advanced & patterns

Debounce & throttle

Debounce waits until the calls stop; throttle runs at most once per interval. Both limit how often a function runs.

  • Debounce: restart a timer on every call and run only after ms of silence. Use it for search-as-you-type, autosave and window-resize end.
  • Throttle: run immediately, then ignore calls until ms has passed. Use it for scroll, mousemove, drag and rate-limited button clicks.
  • Both rely on a closure that keeps the timer id or last-run time between calls.
  • Production versions (lodash) support leading/trailing options, cancel() and flush().
  • For visual updates, requestAnimationFrame throttling syncs work to the display frame rate.

Interview questions

  • Difference between debounce and throttle?
  • Implement debounce.
  • Implement throttle with a trailing call.

Currying, partial application & memoization

Currying turns f(a, b, c) into f(a)(b)(c). Memoization caches results by arguments.

  • Currying turns a function of N arguments into nested functions that each take one argument, which makes reusable specialised functions easy.
  • Partial application fixes some arguments now and the rest later (bind does this). A generic curry uses fn.length to know when to call.
  • Memoization caches the outputs of a pure function, keyed by its inputs. It trades memory for speed and is great for recursive DP (fib) and expensive selectors.
  • Cache keys: one primitive argument can be the key directly. For several arguments use JSON.stringify(args) or a nested Map. For object arguments a WeakMap avoids leaks.
  • React applies the same idea in useMemo, useCallback, React.memo and Reselect selectors.

Interview questions

  • What is currying and why is it useful?
  • Implement sum(1)(2)(3)...() with unlimited calls.
  • What is memoization? Implement it.

Polyfills: bind, map, reduce, Promise.all

Writing a polyfill shows you understand the spec: argument handling, this, ordering and edge cases.

  • A polyfill implements a missing standard feature in older environments. A transpiler (Babel or tsc) rewrites new syntax such as arrows or ?..
  • Attach polyfills to the prototype only if the feature is missing: if (!Array.prototype.x) { ... }. In interviews, use your own names like myMap.
  • Edge cases interviewers look for: this binding, array holes (i in arr), the reduce initial value, preserving result order in Promise.all, the empty input array, and non-promise values.
  • bind: support preset arguments and the new case (bonus point: an instance should ignore the bound this).

Interview questions

  • Polyfill vs transpiler?
  • Implement Promise.all.
  • Implement Array.prototype.filter.

Iterators & generators

An iterable has [Symbol.iterator]. Generators (function*) are pausable functions that make iterators easy.

  • The iterator protocol: an object with next() that returns { value, done }. An iterable has [Symbol.iterator]() that returns an iterator.
  • Built-in iterables: Array, String, Map, Set, arguments and NodeList. They power for...of, spread, destructuring, Array.from and Promise.all.
  • function* returns a generator object. yield pauses and hands out a value, and next(x) resumes and makes yield evaluate to x.
  • Generators are lazy: they produce values on demand, so infinite sequences and pipelines over big data are cheap.
  • Async generators (async function*) with for await...of consume streams and paginated APIs.

Interview questions

  • What is the difference between an iterable and an iterator?
  • What are generators and where are they used?
  • Make a plain object iterable.

Map, Set, WeakMap & memory leaks

Use Map and Set for real collections. Weak versions don't block garbage collection. Know the four classic memory leaks.

  • Map takes any key type (objects too), keeps insertion order, has size, and is faster than plain objects for frequent adds and deletes.
  • Set stores unique values (compared with SameValueZero, so NaN is equal to itself). It gives O(1) has and is handy for de-duplication and lookups.
  • WeakMap and WeakSet hold their (object) keys weakly and cannot be iterated. They are used for private data, caches attached to DOM nodes, and memoizing by object.
  • GC uses mark-and-sweep: anything unreachable from the roots (globals, the stack, closures) gets freed. Reference cycles alone do not leak.
  • Common leaks: forgotten setInterval or listeners, accidental globals, detached DOM nodes still referenced, unbounded caches, and closures holding large objects.

Interview questions

  • Map vs plain object?
  • What is a WeakMap and when would you use it?
  • How does garbage collection work and what causes memory leaks?

Predict-the-output puzzles

Classic trick questions. Explain why each line prints what it does: hoisting, coercion, the event loop, keys.

  • Approach: 1) Mark the sync code. 2) List the microtasks in the order they were queued. 3) Then the macrotasks. Track hoisting and this separately.
  • Object keys are always strings or symbols, so objects used as keys all become '[object Object]'.
  • map(parseInt) passes (value, index), and the index becomes parseInt's radix.
  • A constructor that returns an object overrides this. Returning a primitive is ignored.

Interview questions

  • Why does 3 > 2 > 1 return false?
  • Why does '5' + 3 - 3 give 50?
  • In Puzzle 4, why does p3 print before p2?