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.

  1. 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 or setTimeout), so methods like sleepFirst can still reorder the queue. A sequential for...of with await makes 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 sleepFirst has 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.

  2. 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 with Array.prototype.flatten is the well-known example. Prefer utility functions, or use Object.defineProperty in a polyfill for a real standard method.

    Why the other options are wrong

    • B. An arrow function takes this from the module or script scope, not from the array, so this.map throws a TypeError.

    • C. forEach returns undefined, so the method returns undefined.

    • D. The result is correct, but it changes the original array and returns that same array, which breaks the requirement.

  3. 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 becomes NaN

    • D

      3 ['0', '1', '2'], because the hole becomes undefined

    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.keys lists 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.

  4. 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 replaceAll each 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 foo is wrapped the text contains foo</em>bar, so oba is never found. The result is <em>foo</em>bar<em>baz</em>.

    • C. A regex match consumes its characters, so the overlapping oba is 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>.

  5. 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.name hits the trap with key name. t[key] reads the getter on the target with this === target, so this._name is a plain read of 'target' that bypasses the proxy. Writing return Reflect.get(t, key, receiver) passes the proxy as this, so this._name goes back through the trap and returns 'proxy'. Forwarding with Reflect and 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.

  6. Question 6Asynchronous JavaScript

    fetchJson() returns a promise that rejects. What does getData() 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 the try block 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 the try block at once. The later rejection flows into getData()'s promise and bypasses catch. Writing return await fetchJson() keeps the function suspended inside the try, so the rejection is thrown there and caught. This is the main case where return await is required.

    Why the other options are wrong

    • A. The catch block only sees errors raised while the try block 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.

  7. 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.

  8. Question 8Functions and Data

    Which statements about rest are 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

      rest has no a or b, because rest copies only own properties

    • B

      rest has no d, because rest skips non-enumerable properties

    • C

      rest is { a: 1, b: 2, d: 4 }

    • D

      rest keeps base as its prototype

    • E

      The destructuring throws, because d is 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, so rest is {}. 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 d isn't copied anyway.

  9. Question 9Browser and Interview Coding

    A candidate's placeholder curry decides when to call fn like 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 satisfy fn.length, so join runs 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 fn only when the first fn.length arguments contain no placeholder, for example args.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 join never 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 version join runs before 'a' and 'b' arrive anyway.

  10. 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, and Symbol.keyFor maps it back. Symbols can't be created with new and can't be implicitly converted to strings, which prevents accidental concatenation. Symbol-keyed properties are skipped by Object.keys, for...in and JSON.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.

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.

Go to JavaScript