JAVASCRIPT INTERVIEWS
JavaScript interview questions
300 questions about JavaScript itself, the way interviewers ask them: 112 to explain, 110 where you predict what the code logs, and 78 where you write the function. 106 easy, 133 medium, and 61 hard.
Every question is free to read. Sign in with Google to see the answers: the short version to say in the interview, why it's true, and what they'll ask next.
300 of 300 questions
Types & coercion
- What are the primitive types in JavaScript?
- What does
typeofreturn fornull, arrays, classes, and undeclared variables? - What's the difference between
nullandundefined? - Which values are falsy in JavaScript?
- What's the difference between
==and===? - What do
+and-do when you mix strings and numbers? - What do these string comparisons with
<log? - What's the difference between
isNaNandNumber.isNaN? - Write
getType(value)that returns a precise type name, tellingnull, arrays, and dates apart. - What do these comparisons of
nullandundefinedwith0log? - What do these
==comparisons log, including[] == ![]? - What does
+give when you add arrays and objects, like[] + {}? - What's the difference between
String(value),value.toString(), andvalue + ""? - What do
parseIntandNumberreturn for strings like"12px","", and"1e3"? - What does
["1", "2", "3"].map(parseInt)return? - Why is
0.1 + 0.2 === 0.3false, and how do you compare decimals safely? - What does
toFixedreturn for0.1 + 0.2and for1.005? - What is
Number.MAX_SAFE_INTEGER, and when do you needBigInt? - How can you call methods like
toUpperCaseon a string if primitives aren't objects? - Write
objectIs(a, b), a polyfill forObject.is, without callingObject.is. - How does JavaScript convert an object to a primitive?
- Which of
valueOfandtoStringruns for+, template literals, and*? - What happens past
Number.MAX_SAFE_INTEGER, and when you mix BigInts with numbers? - How do
===,Object.is, and string conversion treat-0? - Write
looseEquals(a, b)that returns the same result asa == b, without using==or!=.
Scope & hoisting
- What are the differences between
var,let, andconst? - What's the difference between function scope and block scope?
- What is hoisting in JavaScript?
- What does this log when a
varand a function are used before they're declared? - What does this log when a function declaration and a function expression are both called before their lines?
- Does
constmake a value immutable? - Which of these top-level declarations become properties of
window? - What do these two loops log when each one schedules a
setTimeoutper iteration? - Fix
createHandlersso each returned function reports its own index and name. - What is the temporal dead zone?
- What does this log when a function reads a name that it declares with
constfurther down? - What is variable shadowing, and when is it not allowed?
- What does this log when a function declares a
varinside anif (false)block? - What is lexical scope, and how does the scope chain find a variable?
- What does this log when a
varand two function declarations share the same name? - What does this script log when it declares
var atwice andlet btwice? - What is an implicit global, and how do you prevent one?
- What does
var a = b = 5inside a function leave behind in the global scope? - Fix
sumandsumRowsso they return the right total and stop leaking globals. - Are class declarations hoisted?
- What do these timers log when the loop body also increments the
letcounter? - What does this log when a
varinside acatchblock has the same name as the catch parameter? - What does this log when a function is declared inside a block in a non-strict script?
- What does this log when a default parameter's closure and the function body both use
x? - How do
evalandwithaffect scope, and why are they avoided?
Functions & closures
- What does it mean that functions are first-class in JavaScript, and what is a higher-order function?
- What is a closure, and what would you use one for?
- What does this greeter log after the variable it closes over changes?
- What do these two wallets created by the same factory log?
- Write
makeCounter(start): a counter withincrement,decrement,reset, andvaluemethods and private state. - Write
createIdGenerator(prefix): each generator returns unique, increasing ids likeuser-1,user-2. - Write
once(fn): a function that runsfnonly the first time it's called. - What is an IIFE, and how does the module pattern use one?
- What is a pure function, and why does it matter?
- What are the differences between a function declaration, a function expression, and an arrow function?
- What's the difference between the
argumentsobject and rest parameters? - What does this function with a default array parameter log?
- What do
lengthandnamereport for these functions? - What does this counter log for its
countproperty after a few increments? - What is a stale closure, and how do you fix one?
- Write
partial(fn, ...presetArgs), withpartial.placeholderto leave gaps you fill in later. - Write
sumso thatsum(1)(2)(3)()returns 6: it keeps adding until it's called with no arguments. - Write
memoizeOne(fn): cache only the most recent call, and recompute when the arguments change. - In what order does this recursive countdown log?
- What causes "Maximum call stack size exceeded", and how do you avoid it in recursive code?
- What does this log after the variables holding two recursive functions are reassigned?
- What does writing to
arguments[0]do to the parameter in each of these functions? - What does this script with a function expression and an IIFE log?
- Can closures cause memory leaks? How, and how do you prevent them?
- Write
trampoline(fn)so a recursive function can run a million steps deep without overflowing the stack.
this & binding
- How does JavaScript decide what
thisrefers to? - What does this log when you call a method through a variable?
- What is
thisin a plain function call, in sloppy mode and in strict mode? - What's the difference between
call,apply, andbind? - How does
thiswork inside an arrow function? - What does this log when an object has a regular method and an arrow function property?
- What is
globalThis, and why was it added? - What does this chain of method calls log, and where does it break?
- Write
calculator(start), whose methods can be chained:calculator(2).add(3).multiply(4).value(). - When more than one
thisbinding rule could apply, which one wins? - Why does a method lose its
thiswhen you pass it as a callback, and how do you fix it? - What does a nested function inside a method see as
this, compared with a nested arrow? - What do these two
setTimeoutcallbacks log forthis.label? - What does
mapreturn here, with and without its second argument? - Can you change the
thisof a function that's already bound? What does this log? - Can
callorbindchange thethisof an arrow function? What does this log? - Implement
Function.prototype.myCallwithout usingcall,apply, orbind. - Implement
Function.prototype.myApplywithout usingcall,apply, orbind. - What happens when you destructure a class method and a class-field arrow off an instance and call them?
- What is
thisinside a DOM event listener? - What does this log when you call a bound constructor with and without
new? - Implement
Function.prototype.myBind, including support fornew. - Which of these calls keep
this: parentheses, the comma operator, or an assignment? - Should you define class methods as arrow function fields so they stay bound? What are the trade-offs?
- A parent constructor calls
this.init()and the child definesinitas an arrow field. What does this log?
Objects & prototypes
- How does the prototype chain work?
- What's the difference between
__proto__andprototype? - What does this log when objects are used as property keys?
- What do
for...in,Object.keys, andReflect.ownKeyslist for this object? - Why put methods on the prototype instead of creating them in the constructor?
- What are getters and setters, and when would you use them?
- What's the difference between
Object.freeze,Object.seal, andObject.preventExtensions? - What does this log after trying to change a frozen object?
- Write a
Shapebase class withCircleandRectanglesubclasses that each compute their own area. - What does this log when an array is put on a constructor's prototype?
- What does this log when a constructor returns a value?
- Implement
myNew(Constructor, ...args)so it does what thenewoperator does. - Write
objectCreate(proto, properties), a polyfill forObject.create. - Implement
myInstanceOf(value, Constructor)so it works like theinstanceofoperator. - Without
class, make aDogconstructor inherit fromAnimalusing prototypes. - What are property descriptors, and what do
writable,enumerable, andconfigurablemean? - In what order does
Object.keyslist these properties? - What's the difference between a shallow and a deep copy of an object, and how do you make each?
- What does
JSON.stringifyproduce for this object? - How do private
#fieldswork, and how are they different from_underscoreproperties or closures? - Are JavaScript classes just syntactic sugar over constructor functions?
- What do
extendsandsuperactually do? - What does this log when a base class constructor calls a method that the subclass overrides?
- What does this log when a static method updates
this.countthrough a subclass? - Write
mixin(Target, ...sources)that adds methods, getters, and setters from plain objects to a class.
Arrays & iteration
- What's the difference between
mapandforEach? - What does this log when the
forEachandmapcallbacks return early? - What's the difference between
sliceandsplice? - What's the difference between
for...inandfor...of, and which should you use on an array? - What does
sort()with no comparator do to an array of numbers? - What do
indexOf,includes,every, andsomereturn in these edge cases? - How do you remove duplicates from an array?
- Write
chunk(array, size)that splits an array into groups ofsizeelements. - Write a generator
range(start, end, step)that yields numbers fromstartup to, but not including,end. - How do you write a comparator for
sort, and what are the common mistakes? - Which array methods mutate the array, and what are
toSorted,toReversed,toSpliced, andwith? - What does
reducedo here when you don't pass an initial value? - What does this log for a grid built with
fill([])and one built withArray.from? - What does this log about
new Array(n),Array.of, and writing tolength? - What do these
flatandflatMapcalls return? - What is an array-like object, and how do you turn one into a real array?
- Implement
Array.prototype.mapyourself, asmyMap. - Write
groupBy(items, getKey)that groups items into an object of arrays, without usingObject.groupBy. - Write
rotate(array, k)that rotates an arrayksteps to the right. - What does this generator log when you pass values into
next()? - What is the iteration protocol, and what's the difference between an iterable and an iterator?
- How do array methods treat the hole in
[1, , 3]? - What does this log when you
breakout of a loop over a generator and then reuse it? - Implement
Array.prototype.reduceyourself, asmyReduce. - Write a
Rangeclass whose instances work withfor...ofand spread, without using a generator.
The event loop
- What is the event loop?
- Does
setTimeout(fn, 0)runfnbefore the next line? What does this log? - In what order do a resolved promise's
thenand a zero-delaysetTimeoutrun? - What's the difference between a task and a microtask?
- When does a promise's executor run, and when does its
thencallback run? - How much of an
asyncfunction runs before its caller continues? - Several timers with different delays: in what order do they fire?
- The script throws an uncaught error. Do the callbacks it already scheduled still run?
- What happens when a long synchronous function blocks the main thread, and how do you avoid it?
- A promise callback queues another microtask. Does it still run before a pending timeout?
- Two promise chains start at the same time. How do their callbacks interleave?
- Timers queue promises and promises queue timers here. In what order does it log?
- What does the classic
async1/async2ordering puzzle log? - An
asyncfunction awaits anotherasyncfunction. How does it interleave with athenchain? - A promise is resolved inside a timer. When does the code after its
awaitrun? - Does
setTimeout(fn, 1000)runfnafter exactly 1000 ms? - What's the difference between
setIntervaland a recursivesetTimeout, and why do timers drift? - Where does
requestAnimationFramerun in the event loop? - Write
processInChunks(items, fn, chunkSize): map a large array without blocking the main thread. - Write
createBatcher(flush): collect values scheduled in the same synchronous run and pass them toflushonce, in a microtask. - Timers inside microtasks and microtasks inside timers: in what order do the letters log?
- A
thencallback returns an already-resolved promise. Where does its value show up among the numbers? - A
thencallback schedules timers and returns a promise that a timer resolves. What's the order? - What is microtask starvation, and how can a loop of promises freeze the page?
- In Node.js, where do
process.nextTickandsetImmediatefit in the event loop?
Promises & async/await
- What are the three states of a promise, and how is resolved different from fulfilled?
- What does this log when the executor calls
resolvetwice and thenreject? - What does
thenreturn, and how does that make promise chaining work? - What does this promise chain log when one
thencallback forgets to return? - Which callbacks in this chain run after a
thencallback throws? - What does an
asyncfunction return, and what doesawaitdo? - Write
promisify(fn): turn a Node-style callback function into one that returns a promise. - Write
runInSeries(tasks): run async functions one after another and collect their results. - Write
promiseRace(iterable), a polyfill forPromise.race. - What does this log, and why doesn't the first
then's error handler catch the error? - What does
finallydo with return values and errors in this code? - These two
awaits run one after the other. How do you make them run in parallel? - What does this log when
forEachis given anasynccallback? - What's the difference between
Promise.all,Promise.allSettled,Promise.race, andPromise.any? - Write
promiseAll(iterable), a polyfill forPromise.all. - Write
promiseAllSettled(iterable), a polyfill forPromise.allSettled. - Write
promiseAny(iterable), a polyfill forPromise.any. - Write
withTimeout(promise, ms): reject if a promise takes longer thanmsto settle. - Write
retry(fn, { retries, delay }): call an async function again when it fails. - What are async iterators, and when would you use
for await...of? - What is an unhandled promise rejection, and how do you avoid one?
- What does this log when you
awaitan object that has athenmethod? - What does this log, and why does only one of these
try/catchblocks catch the rejection? - Promises can't be cancelled. How do you make your own async function cancellable with
AbortController? - Write
mapWithLimit(items, limit, fn): run an async function over a list, at mostlimitcalls at a time.
Modern syntax & collections
- What's the difference between
??and||? - What does optional chaining (
?.) do? - What is destructuring, and how do defaults and renaming work?
- Which variables does this nested destructuring with renaming create?
- What's the difference between spread and rest syntax?
- What do these object spreads produce when keys overlap?
- What does this object literal with computed keys log?
- What do
at()and bracket access return for these indexes? - Write
pick(obj, keys)andomit(obj, keys). - Which destructuring defaults are used here, and what happens with
null? - When would you use a
Mapinstead of a plain object? - How do
MapandSetcompare keys in this snippet? - Write
countWords(text): count how often each word appears, using aMap. - Write
union,intersection, anddifferencefor two Sets. - What is a
Symbol, and what would you use one for? - Which of these operations see a symbol-keyed property?
- What is a
WeakMap, and when would you use one instead of aMap? - What does
Object.groupByreturn in this example? - How do tagged templates work, and what does the tag function receive?
- What does this tag function receive and return?
- Write an
htmltagged template that escapes every interpolated value. - How far does optional chaining short-circuit in this code?
- What do
||=,??=, and&&=do here, including on aconst? - Why does the second destructuring swap here fail?
- What are
WeakRefandFinalizationRegistry, and why should you rarely use them?
Errors, strict mode & modules
- How do
try,catch, andfinallywork together? - In what order do
try,catch, andfinallylog whencatchreturns? - Which built-in error type does each of these mistakes throw?
- What does
catchreceive when the code throws a string or a plain object? - Can you write a
catchblock without an error variable, and when would you? - Write
safeJsonParse(text)that returns[error, value]instead of throwing. - Write an
assert(condition, message)helper that throws anAssertionErrorwhen the condition is falsy. - What is strict mode, and how do you turn it on?
- What's the difference between named and default exports?
- What happens when
finallyhas its ownreturn? - Does this
try/catchcatch the error thrown in thesetTimeoutcallback? - What does
error.causegive you when you wrap one error in another? - This
catchhandles only one kind of error. What gets logged? - Build an error class hierarchy: a base
AppErrorwithValidationErrorandNotFoundErrorsubclasses. - How do you catch errors that nothing else handled, with the
errorandunhandledrejectionevents? - What are the differences between ES modules and CommonJS?
- What does it mean that ES module imports are live bindings?
- How is the top level of an ES module different from the top level of a classic script?
- How does
<script type="module">behave differently from a classic<script>? - What is dynamic
import(), and when would you use it? - Does changing a variable in
finallychange what the function returns? - What does this log, given that one function runs in strict mode and the other doesn't?
- Imports in ES modules are hoisted. What does that mean, and in what order do these modules run?
- What happens when two ES modules import each other?
- What is tree shaking, and what can stop it from working?
Browser & DOM
- What are event bubbling and capturing?
- What is event delegation, and why would you use it?
- Why doesn't
removeEventListenerremove my listener? - What's the difference between
DOMContentLoadedandload? - What's the difference between
innerHTMLandtextContent, and why does it matter for security? - Write
escapeHtml(str)so a string can be safely put inside HTML. - What's the difference between
localStorage,sessionStorage, and cookies? - Does
fetchreject when the server responds with a 404 or a 500? - Write
toQueryString(params)that turns an object into a URL query string. - What's the difference between
stopPropagation,stopImmediatePropagation, andpreventDefault? - What are passive event listeners, and why do they make scrolling smoother?
- How do you create and dispatch a custom DOM event?
- Write
delegate(root, type, selector, handler)for event delegation. - What's the difference between a plain
<script>,<script async>, and<script defer>? - How do you cancel a
fetchrequest, and how do you give it a timeout? - Write
parseQuery(query)that turns a URL query string into an object. - Write a
localStoragewrapper whose entries expire after a given time. - Why use
IntersectionObserverinstead of a scroll listener to detect when an element becomes visible? - How do you animate with
requestAnimationFrame, and why is it better thansetInterval? - What are Web Workers, and when would you use one?
- What are reflow and repaint, and what is layout thrashing?
- What is the same-origin policy, and how does CORS work, including preflight requests?
- How do you communicate safely between windows or iframes with
postMessage? - What causes memory leaks in a frontend app, and how do you find them?
- Write a tiny client-side router that matches paths like
/users/:id.
Coding challenges
- Write
debounce(fn, wait): callfnonly afterwaitms have passed without another call. - Write
flatten(array, depth)to flatten nested arrays up todepthlevels, without usingflat. - Write
pipe(...fns)andcompose(...fns)that combine functions into one. - Write
get(object, path, defaultValue)to read a nested value by a path likea.b[0].c. - Write
classNames(...args)to build a CSS class string from strings, objects, and arrays. - Write
deepFreeze(object)so that an object and everything reachable from it is frozen. - Write
uniqueBy(array, key)to remove duplicates by a computed key, keeping the first of each. - Write
throttle(fn, wait)so thatfnruns at most once everywaitms. - Write
memoize(fn, resolver)that caches results by a key computed from the arguments. - Write
curry(fn)that collects arguments over several calls until it hasfn.lengthof them. - Write
set(object, path, value)to write a nested value, creating missing objects and arrays on the way. - Write
flattenObject(object)to turn a nested object into a single level with dotted keys. - Write
unflattenObject(object)to rebuild a nested object from dotted keys. - Write
render(template, data)that fills{{ path }}placeholders with values fromdata. - Write
camelCase(text)andkebabCase(text)to convert between naming styles. - Write an
EventEmitterclass withon,off,once, andemit. - Implement an
LRUCacheclass withgetandputthat evicts the least recently used entry. - Write a Redux-style
createStore(reducer, initialState)withgetState,dispatch, andsubscribe. - Write a minimal
Observableclass withsubscribe, unsubscribe, teardown, and amapmethod. - Write
debounce(fn, wait, { leading, trailing })withcancel()andflush()methods. - Extend
curry(fn)with a placeholder, soadd3(_, 2)(1, 3)fills the skipped argument later. - Write
deepEqual(a, b)that compares values structurally, includingMap,Set,Date, and cyclic objects. - Write
deepClone(value)that copies nested data and handles cycles,Map,Set, andDate. - Implement an LRU cache with O(1)
getandputusing a hash map and a doubly linked list. - Build tiny reactive signals:
signal,computed, andeffectwith automatic dependency tracking.