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
- 8 types: 7 primitives (
string number bigint boolean undefined null symbol) +object.typeof null === 'object'is a historic bug; useArray.isArrayfor arrays. ===compares without coercion;==coerces first. Onlynull == undefinedis a handy==case.NaNis never equal to itself, so useNumber.isNaNorObject.is.- Falsy values:
false 0 -0 0n '' null undefined NaN. Everything else, including[],{}and'0', is truthy. varis function-scoped and hoisted asundefined.let/constare block-scoped and hoisted but sit in the TDZ until their line runs.conststops reassignment, not mutation.- 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. thisis decided at call time:new>bind/call/apply>obj.method()> default (undefinedin strict mode). Arrow functions have no ownthis; they use the enclosing one.- Objects inherit through the prototype chain.
classis syntax over prototypes;extendslinksChild.prototypetoParent.prototype. - Spread and
Object.assigncopy shallowly. UsestructuredClonefor deep copies (it keeps Date, Map, Set and cycles, but not functions). - Event loop: run all sync code, then empty every microtask (promise callbacks,
awaitcontinuations,queueMicrotask), then take one macrotask (timer, I/O, event), and repeat. Promise.allfails fast;allSettlednever rejects;racesettles with the first to settle;anyresolves with the first success (AggregateErrorif all fail).asyncfunctions always return a promise.awaitpauses only that function. UsePromise.allfor parallel work, and remember thatforEachdoes not wait for async callbacks.- Events go through capture → target → bubble. Delegation means one listener on a parent plus
e.target.closest(...). - Debounce waits until the calls stop (search box). Throttle runs at most once per interval (scroll, resize).
- ESM (
import/export) is static, async and live-bound, and allows tree-shaking. CommonJS (require) is dynamic, synchronous and copies values. - Use
Mapfor any key type, ordered entries and frequent adds and deletes.WeakMapuses 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. numberis a 64-bit float. Integers are safe up toNumber.MAX_SAFE_INTEGER(2^53 − 1). UseBigInt(10n) beyond that.undefinedmeans “not assigned yet”, whilenullmeans “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
nullandundefined? - 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 asifand&&. +with any string concatenates:1 + '2'is'12'.-,*and/convert to numbers:'3' - 1is2.- Objects become primitives through
Symbol.toPrimitive, thenvalueOf, thentoString. That is why[] + {}is'[object Object]'. ==rules in short:null == undefinedand nothing else is equal to them; otherwise both sides are usually converted to numbers.Object.is(a, b)is like===except thatNaNequalsNaNand+0does 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 (
{}) forlet/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/constare hoisted too but stay in the Temporal Dead Zone until their declaration executes, so accessing them throwsReferenceError.- A
letin aforloop 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
varloop withsetTimeoutprint 3, 3, 3? - Can you change a
constobject?
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,setTimeoutanddebounce. - Default parameters (
b = 10), rest (...args) and spread (f(...arr)) replaced the oldargumentsobject. - 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?.candfn?.()stop and returnundefinedwhen 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.
maptransforms every item,filterkeeps some, andreducefolds everything into one value (sum, group-by, an object).find/findIndexreturn the first match,someandeveryshort-circuit, andincludesuses SameValueZero (so it findsNaN).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,toSplicedandwith(index, value).
Interview questions
- Difference between
mapandforEach? - Difference between
sliceandsplice? - 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()givesundefinedin strict mode or modules, andglobalThisin sloppy mode. - Implicit binding:
obj.f()setsthistoobj. Pulling the method out (const g = obj.f) loses it. - Explicit binding:
f.call(ctx, a, b),f.apply(ctx, [a, b]), orf.bind(ctx), which returns a new permanently bound function. - new binding:
new F()creates a fresh object and setsthisto it. - Arrow functions ignore all of these rules and use the enclosing
this. Class field arrows liketick = () => {}auto-bind to the instance.
Interview questions
- Explain
call,applyandbind. - What is
thisinside an arrow function? - Why does a method lose
thiswhen 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 withObject.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
.prototypeobject.new F()creates an object whose[[Prototype]]isF.prototype. classaddsextends/super, static members, getters and setters, and#privatefields. 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__andprototype? - What does the
newkeyword 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 losesundefined, 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.freezeblocks adding, removing and changing properties one level deep.Object.sealallows 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 NodesetImmediate. - Microtasks: promise
then/catch/finally, code afterawait,queueMicrotask,MutationObserver. In Node,process.nextTickruns 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.nextTickvssetImmediatein 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/rejectcalls are ignored. thenalways 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)isthen(undefined, fn)and recovers the chain unless it re-throws.finallygets 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.allvsallSettledvsracevsany?- 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
asyncfunction always returns a promise. Areturn vresolves it and athrowrejects it. awaitunwraps a promise. The rest of the function continues later as a microtask, and other code runs meanwhile.- Handle errors with
try/catch/finallyaround awaits, or attach.catchto 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
awaitworks in ES modules (and Node.mjs).for await...ofconsumes 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
forEachwork withawait?
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.targetis the element that was actually clicked.e.currentTargetis 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 nopreventDefault(smooth scrolling), and{ signal }removes it viaAbortController.
Interview questions
- What is event bubbling and capturing?
- What is event delegation and why use it?
- Difference between
e.targetande.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 ofmodule.exportsat that moment. - ESM runs in strict mode, has top-level
await, and its top-levelthisisundefined. CommonJS wraps each file in a function that providesrequire,module,exportsand__dirname. - Node uses ESM when the file is
.mjsorpackage.jsonhas"type": "module". Otherwise.jsis 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.
localStoragepersists until it is cleared.sessionStoragelasts 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
idbor Dexie make it easier. - The
storageevent fires in other tabs whenlocalStoragechanges, 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
msof silence. Use it for search-as-you-type, autosave and window-resize end. - Throttle: run immediately, then ignore calls until
mshas 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/trailingoptions,cancel()andflush(). - For visual updates,
requestAnimationFramethrottling 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 (
binddoes this). A genericcurryusesfn.lengthto 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 aWeakMapavoids leaks. - React applies the same idea in
useMemo,useCallback,React.memoand 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 likemyMap. - Edge cases interviewers look for:
thisbinding, array holes (i in arr), the reduce initial value, preserving result order inPromise.all, the empty input array, and non-promise values. bind: support preset arguments and thenewcase (bonus point: an instance should ignore the boundthis).
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,
argumentsand NodeList. They powerfor...of, spread, destructuring,Array.fromandPromise.all. function*returns a generator object.yieldpauses and hands out a value, andnext(x)resumes and makesyieldevaluate tox.- Generators are lazy: they produce values on demand, so infinite sequences and pipelines over big data are cheap.
- Async generators (
async function*) withfor await...ofconsume 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.
Maptakes any key type (objects too), keeps insertion order, hassize, and is faster than plain objects for frequent adds and deletes.Setstores unique values (compared with SameValueZero, soNaNis equal to itself). It gives O(1)hasand is handy for de-duplication and lookups.WeakMapandWeakSethold 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
setIntervalor 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
thisseparately. - 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 > 1return false? - Why does
'5' + 3 - 3give 50? - In Puzzle 4, why does p3 print before p2?