JavaScript interview questions and answers
10 questions from the JavaScript Interview Mock practice bank, spread across its domains. Pick your answer, then open the explanation to see why each option is right or wrong.
- Question 1Asynchronous JavaScript
What is logged, and when?
const wait = (s) => new Promise((r) => setTimeout(r, s * 1000)); class LazyMan { constructor(name) { this.tasks = [() => console.log(`Hi, I'm ${name}`)]; queueMicrotask(async () => { for (const task of this.tasks) await task(); }); } eat(food) { this.tasks.push(() => console.log(`Eat ${food}`)); return this; } sleep(s) { this.tasks.push(() => wait(s).then(() => console.log(`Wake up after ${s}`))); return this; } sleepFirst(s) { this.tasks.unshift(() => wait(s).then(() => console.log(`Wake up after ${s}`))); return this; } } new LazyMan('Jack').eat('apple').sleepFirst(1).sleep(2).eat('banana');- A
Straight away:
Hi, I'm Jack,Eat apple; after 1 s:Wake up after 1; 2 s later:Wake up after 2,Eat banana - B
After 1 s:
Wake up after 1,Hi, I'm Jack,Eat apple; 2 s later:Wake up after 2,Eat banana - C
Straight away:
Hi, I'm Jack,Eat apple,Eat banana; the two wake-up lines come later - D
Nothing for 3 s, then all five lines at once
Show the answer and explanation
Answer: B
LazyMan-style chaining has two parts: every method only records a task and returns
this, and execution starts after the synchronous chain has finished (a microtask orsetTimeout), so methods likesleepFirstcan still reorder the queue. A sequentialfor...ofwithawaitmakes each step wait for the one before it.Why the other options are wrong
A. The queue only starts in a microtask, after the whole chain has run, so
sleepFirsthas already moved its task to the front.C. That happens when tasks are started without awaiting them. Here
await task()waits for each sleep promise.D. Each task logs as soon as it runs; only the steps after a sleep are delayed.
- A
- Question 2Types, Values and Objects
Add
square()to arrays so that[1, 2, 3].square()returns a new array[1, 4, 9]and leaves the original unchanged. Which definition works?- A
Array.prototype.square = function () { return this.map((x) => x * x); }; - B
Array.prototype.square = () => this.map((x) => x * x); - C
Array.prototype.square = function () { return this.forEach((x) => x * x); }; - D
Array.prototype.square = function () { for (let i = 0; i < this.length; i++) this[i] **= 2; return this; };
Show the answer and explanation
Answer: A
The interviewer's next question is usually "Should you do this in production?" The answer is no, not for built-ins you do not own. Plain assignment makes the property enumerable (it appears in
for...in), and it can clash with future standard methods. The "SmooshGate" problem withArray.prototype.flattenis the well-known example. Prefer utility functions, or useObject.definePropertyin a polyfill for a real standard method.Why the other options are wrong
B. An arrow function takes
thisfrom the module or script scope, not from the array, sothis.mapthrows aTypeError.C.
forEachreturnsundefined, so the method returnsundefined.D. The result is correct, but it changes the original array and returns that same array, which breaks the requirement.
- A
- Question 3Functions and Data
What does this log?
const a = [1, , 3]; const doubled = a.map(x => x * 2); console.log(doubled.length, Object.keys(doubled));- A
2 ['0', '1'], because map drops the hole - B
3 ['0', '2'] - C
3 ['0', '1', '2'], because the hole becomesNaN - D
3 ['0', '1', '2'], because the hole becomesundefined
Show the answer and explanation
Answer: B
Most ES5 array methods (forEach, map, filter, some, every, reduce) skip holes. map creates a result of the same length and simply doesn't define the skipped index, so the hole survives.
Object.keyslists only the defined indices, '0' and '2'.Why the other options are wrong
A. map keeps the array's length; it doesn't compact anything.
C. The callback never runs for the hole, so no NaN is produced.
D. map preserves holes; it does not fill them in.
- A
- Question 4Browser and Interview Coding
highlight('foobarbaz', ['foo', 'oba', 'baz'])must wrap every keyword match in<em>. Overlapping matches merge into one tag, so the expected result is'<em>fooba</em>r<em>baz</em>'. Which approach produces it?- A
Mark every character index covered by any match in a boolean array, then wrap each run of marked characters in one
<em> - B
For each keyword, run
text = text.replaceAll(kw, '<em>' + kw + '</em>') - C
Build
new RegExp(keywords.join('|'), 'g')and wrap each match - D
Sort keywords by length, longest first, then
replaceAlleach one
Show the answer and explanation
Answer: A
Treat highlighting as an interval problem: find every match range, merge overlapping or touching ranges, then build the output in one pass. A boolean mask is the simplest way to merge. Sorting the ranges and merging them is the O(m log m) alternative. Replacing text in place corrupts later searches. All four approaches were run in Node.
Why the other options are wrong
B. After
foois wrapped the text containsfoo</em>bar, soobais never found. The result is<em>foo</em>bar<em>baz</em>.C. A regex match consumes its characters, so the overlapping
obais skipped. Special characters in keywords would also need escaping.D. The keywords here all have the same length, and each replacement still breaks the overlapping matches. The output is still
<em>foo</em>bar<em>baz</em>.
- A
- Question 5Modern Language and the Engine
What does this log?
const target = { _name: 'target', get name() { return this._name; }, }; const proxy = new Proxy(target, { get(t, key, receiver) { if (key === '_name') return 'proxy'; return t[key]; }, }); console.log(proxy.name);- A
'target' - B
'proxy' - C
undefined - D
A TypeError, because the trap ignores its receiver
Show the answer and explanation
Answer: A
proxy.namehits the trap with keyname.t[key]reads the getter on the target withthis === target, sothis._nameis a plain read of'target'that bypasses the proxy. Writingreturn Reflect.get(t, key, receiver)passes the proxy asthis, sothis._namegoes back through the trap and returns'proxy'. Forwarding withReflectand the receiver keeps getters, setters and inheritance consistent.Why the other options are wrong
B. That needs
Reflect.get(t, key, receiver), which runs the getter with this as the proxy.C. The getter does run, and it finds _name on the target.
D. Ignoring receiver is allowed; it only changes which this the getter sees.
- A
- Question 6Asynchronous JavaScript
fetchJson()returns a promise that rejects. What doesgetData()produce?async function getData() { try { return fetchJson(); } catch (e) { return 'fallback'; } }- A
A promise that fulfils with
"fallback" - B
A promise that rejects with
fetchJson's error, because thetryblock finished before the rejection - C
A promise that fulfils with the rejected promise itself
- D
A synchronous exception that escapes from
getData()
Show the answer and explanation
Answer: B
return fetchJson()hands the pending promise back as the async function's result and leaves thetryblock at once. The later rejection flows intogetData()'s promise and bypassescatch. Writingreturn await fetchJson()keeps the function suspended inside thetry, so the rejection is thrown there and caught. This is the main case wherereturn awaitis required.Why the other options are wrong
A. The
catchblock only sees errors raised while thetryblock runs, and none is raised there.C. An async function adopts a returned promise; it never fulfils with one.
D. Async functions report every failure through their returned promise.
- A
- Question 7Types, Values and Objects
Which loose comparisons evaluate to
true? (Choose two.)Choose 2.
- A
"" == 0 - B
"0" == false - C
null == 0 - D
undefined == 0 - E
"false" == false
Show the answer and explanation
Answer: A and B
In ==, a boolean always converts to a number first (false becomes 0, true becomes 1), and a string compared with a number converts with ToNumber. So "0" == false is "0" == 0, which is 0 == 0. But "false" converts to NaN, so "false" == false is false. null and undefined are only ever == to each other.
Why the other options are wrong
C. null only loosely equals undefined; it is never converted to a number here.
D. undefined only loosely equals null.
E. false becomes 0, but "false" converts to NaN, and NaN equals nothing.
- A
- Question 8Functions and Data
Which statements about
restare true after this code runs? (Choose two.)const base = { a: 1, b: 2 }; const obj = Object.create(base); obj.c = 3; Object.defineProperty(obj, 'd', { value: 4, enumerable: false }); const { c, ...rest } = obj;Choose 2.
- A
resthas noaorb, because rest copies only own properties - B
resthas nod, because rest skips non-enumerable properties - C
restis{ a: 1, b: 2, d: 4 } - D
restkeepsbaseas its prototype - E
The destructuring throws, because
dis not writable
Show the answer and explanation
Answer: A and B
Object rest (and object spread) copy own, enumerable properties into a new plain object. Here the only own enumerable properties are
c(taken out by name) and nothing else, sorestis{}. The same rules explain why spreading a class instance loses its methods: they live on the prototype.Why the other options are wrong
C. It holds neither the inherited keys nor the non-enumerable one.
D. Rest creates a fresh plain object whose prototype is Object.prototype.
E. Reading a property doesn't need it to be writable, and
disn't copied anyway.
- A
- Question 9Browser and Interview Coding
A candidate's placeholder
currydecides when to callfnlike this:function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn.apply(this, args); return (...next) => { const merged = args.map((a) => a === curry.placeholder && next.length ? next.shift() : a); return curried.apply(this, [...merged, ...next]); }; }; } curry.placeholder = Symbol('_'); const _ = curry.placeholder; const join = (a, b, c) => `${a}_${b}_${c}`; curry(join)(_, _, 'c')('a')('b');What happens on the last line?
- A
It returns
'a_b_c' - B
It returns a function, because the first call is still waiting for its placeholders to be filled
- C
It throws a
TypeError: three arguments satisfyfn.length, sojoinruns at once with two symbol placeholders, and a template literal can't convert a symbol to a string - D
It returns
'c_a_b'
Show the answer and explanation
Answer: C
The completion condition is the subtle part of placeholder currying: call
fnonly when the firstfn.lengtharguments contain no placeholder, for exampleargs.length >= fn.length && args.slice(0, fn.length).every((a) => a !== curry.placeholder). Interviewers often give the basic curry first, then add placeholders to see whether you update this check.Why the other options are wrong
A. That is the intended result, but
joinnever gets to see'a'and'b'.B. That is how it should behave, but the length check counts placeholders as real arguments, so it does not wait.
D. Placeholders hold their positions;
'c'stays third. And in this versionjoinruns before'a'and'b'arrive anyway.
- A
- Question 10Modern Language and the Engine
Which two statements about symbols are true? (Choose two.)
Choose 2.
- A
Symbol.for('app')returns the same symbol every time it is called with'app' - B
Symbol.keyFor(Symbol('app'))returns'app' - C
new Symbol('x')creates a symbol wrapped in an object - D
'id: ' + Symbol('x')throws a TypeError - E
Object.keys()lists symbol-keyed properties after the string keys
Show the answer and explanation
Answer: A and D
Symbol()always makes a unique value;Symbol.for(key)shares one through a global registry, andSymbol.keyFormaps it back. Symbols can't be created withnewand can't be implicitly converted to strings, which prevents accidental concatenation. Symbol-keyed properties are skipped byObject.keys,for...inandJSON.stringify.Why the other options are wrong
B. keyFor only knows registry symbols; for a plain Symbol() it returns undefined.
C. Symbol is not a constructor; calling it with new throws a TypeError.
E. Object.keys returns only string keys; use Object.getOwnPropertySymbols or Reflect.ownKeys.
- A
Practise all 688 JavaScript questions
Start with the free 15-question diagnostic. It shows where to focus, and your results carry over if you sign up.