quizzx

Sign in

JavaScript interview questions for live coding

Here are 11 practical JavaScript interview questions you can paste into a shared editor, from warm-up to senior. Each has starter code that has been run, what a good answer shows, and one follow-up. They test the language itself, with no framework and no DOM: closures, this, promises and timers.

Try it in a pad2 free interviews, no card needed.

How to use these

Pick one warm-up and one core or senior question for a 45 minute interview. Paste the code block into a pad before the candidate joins. The lines marked // => show what a correct answer prints, so the candidate can run the file and check their own work.

Some questions are a function to write. Others are working code with a bug, because reading code is most of the job. For how to choose and pace a question, see our guide to technical interview questions.

The questions

  1. 1. Group by a key Warm-up

    Write groupBy(items, keyFn). It returns an object whose keys are the results of keyFn and whose values are arrays of the matching items, in their original order.

    function groupBy(items, keyFn) {
    }
    
    // Examples
    const words = ["apple", "avocado", "banana"]
    console.log(JSON.stringify(groupBy(words, w => w[0])))  // => {"a":["apple","avocado"],"b":["banana"]}
    console.log(JSON.stringify(groupBy([], w => w)))  // => {}
    

    A good answer shows: A plain loop or a reduce, written without fuss. Either is fine. What matters is that they can read it back to you.

    Follow-up: Object.groupBy now does this. What is different about the object it returns?

  2. 2. The method that lost its object Warm-up

    Passing counter.increment as a callback throws. Ask the candidate to explain why and to show two different fixes.

    class Counter {
      constructor() { this.count = 0 }
      increment() { this.count += 1 }
    }
    
    const counter = new Counter()
    const increment = counter.increment
    try {
      increment()
    } catch (err) {
      console.log(err.constructor.name)  // => TypeError
    }
    

    A good answer shows: They can say what this is at the call site, and they know bind, an arrow function wrapper, or an arrow class field. This bug shows up in every event handler.

    Follow-up: Which fix would you choose in a class with 20 methods, and why?

  3. 3. Keep the latest row per id Core

    Rows arrive in any order. Return one row per id, the one with the highest updatedAt. Keep ids in the order they first appear.

    const rows = [
      { id: 1, name: "Ana", updatedAt: 5 },
      { id: 2, name: "Bo", updatedAt: 3 },
      { id: 1, name: "Ana M.", updatedAt: 9 },
      { id: 2, name: "B", updatedAt: 1 },
    ]
    
    function latest(rows) {
    }
    
    // Examples
    console.log(JSON.stringify(latest(rows)))
    // => [{"id":1,"name":"Ana M.","updatedAt":9},{"id":2,"name":"Bo","updatedAt":3}]
    

    A good answer shows: A Map keyed by id, one pass, and knowledge that a Map keeps insertion order. The last row is older than the one before it, which catches "last one wins".

    Follow-up: The input is 5 million rows read from a stream. What changes?

  4. 4. Flatten nested keys Core

    Turn a nested object into a flat one whose keys are dotted paths. Arrays and other values are left as they are.

    function flatten(obj) {
    }
    
    // Examples
    const config = { db: { host: "x", pool: { max: 5 } }, tags: ["a"], debug: false }
    console.log(JSON.stringify(flatten(config)))
    // => {"db.host":"x","db.pool.max":5,"tags":["a"],"debug":false}
    

    A good answer shows: Recursion with a prefix, and a correct test for "is a plain object". null and arrays are the two values that trip people up.

    Follow-up: Write the inverse. What input makes the round trip lossy?

  5. 5. Debounce Core

    Write debounce(fn, ms). The returned function waits until ms have passed with no new call, then calls fn once with the latest arguments.

    function debounce(fn, ms) {
    }
    
    // Examples
    const save = debounce(text => console.log("saved", text), 50)
    save("h")
    save("he")
    save("hey")  // => saved hey
    

    A good answer shows: A timer held in a closure, cleared on every call. Ask where they would use it: search boxes and autosave are the usual answers.

    Follow-up: Add a cancel method. Then explain how throttle differs.

  6. 6. The save that reports zero Core

    saveAll should resolve to the number of items saved. It prints 0. Ask the candidate to explain why and fix it so it prints 3.

    const saved = []
    const save = async item => {
      await new Promise(resolve => setTimeout(resolve, 10))
      saved.push(item)
    }
    
    async function saveAll(items) {
      items.forEach(async item => {
        await save(item)
      })
      return saved.length
    }
    
    saveAll([1, 2, 3]).then(n => console.log(n))  // => 0
    

    A good answer shows: They know forEach ignores the promises its callback returns. A for...of loop saves one at a time. Promise.all with map saves all at once. They should say which they chose.

    Follow-up: One save rejects. What happens in each of your two versions?

  7. 7. Load everything, keep the failures Core

    Load all ids at the same time. Return the results in the order of the ids. Where a load fails, put the error message in its place instead of rejecting.

    const fakeFetch = id => new Promise((resolve, reject) => {
      setTimeout(() => (id === 2 ? reject(new Error("not found")) : resolve({ id })), 20)
    })
    
    async function loadAll(ids) {
    }
    
    // Examples
    loadAll([1, 2, 3]).then(result => console.log(JSON.stringify(result)))
    // => [{"id":1},"not found",{"id":3}]
    

    A good answer shows: Promise.allSettled, or Promise.all with a catch on each promise. Either way they start every request before waiting for any.

    Follow-up: How would you tell a caller which entries are errors, without guessing from the type?

  8. 8. A small event emitter Core

    Build an emitter with on, off, once and emit. Listeners run in the order they were added.

    class Emitter {
    }
    
    // Examples
    const emitter = new Emitter()
    const log = name => console.log("hello", name)
    emitter.on("greet", log)
    emitter.once("greet", name => console.log("first", name))
    emitter.emit("greet", "Ana")
    // => hello Ana
    // => first Ana
    emitter.emit("greet", "Bo")  // => hello Bo
    emitter.off("greet", log)
    emitter.emit("greet", "Cy")
    

    A good answer shows: A Map of arrays or sets, and a once that removes itself. The stub throws on the first on(), which is a fair first step to talk through.

    Follow-up: A listener calls off() on itself during emit. Does your loop skip the next listener?

  9. 9. Memoize Core

    Write memoize(fn) for a function of one argument, so a repeated call with the same argument does not call fn again.

    function memoize(fn) {
    }
    
    // Examples
    let calls = 0
    const square = memoize(n => { calls += 1; return n * n })
    console.log(square(4), square(4), square(5), calls)  // => 16 16 25 2
    

    A good answer shows: A Map in a closure, and a check with has() so that a cached undefined or 0 still counts as cached.

    Follow-up: Support several arguments. Then: this cache grows forever. What would you do about it?

  10. 10. A promise with a deadline Senior

    Write withTimeout(promise, ms). It settles like the promise if that happens within ms, and otherwise rejects with an Error whose message is "timeout".

    const wait = (ms, value) => new Promise(resolve => setTimeout(() => resolve(value), ms))
    
    function withTimeout(promise, ms) {
    }
    
    // Examples
    withTimeout(wait(10, "fast"), 50).then(v => console.log(v))  // => fast
    withTimeout(wait(200, "slow"), 50).catch(err => console.log(err.message))  // => timeout
    

    A good answer shows: Promise.race, and a timer that is cleared when the promise wins. Without that, a script stays alive for the full timeout.

    Follow-up: After the timeout, is the slow work still running? How would you stop a real fetch?

  11. 11. Map with a concurrency limit Senior

    Write mapLimit(items, limit, fn). It calls the async fn on every item with at most limit calls in flight, and resolves to the results in input order.

    let running = 0
    let peak = 0
    const work = async n => {
      running += 1
      peak = Math.max(peak, running)
      await new Promise(resolve => setTimeout(resolve, 20))
      running -= 1
      return n * 2
    }
    
    async function mapLimit(items, limit, fn) {
    }
    
    // Examples
    mapLimit([1, 2, 3, 4, 5], 2, work).then(result => console.log(JSON.stringify(result), peak))
    // => [2,4,6,8,10] 2
    

    A good answer shows: A shared index and limit workers that each pull the next item, or a pool of pending promises. Results are written by index, not pushed.

    Follow-up: One call rejects. What should the others do, and what does your code do today?

Run them with a candidate

Every snippet here runs on Node with no packages. If you want a pad that both of you can type in and run, QuizzX is JavaScript0/month per team for unlimited interviews, and the first 2 are free. See the online code editor for interviews page or the pricing.

Questions

Do these questions need a browser?
No. They run on Node with no packages and do not touch the DOM. Each snippet has been run.
Can I use them for a React or front-end role?
Yes, as a test of the language under the framework. Closures, this, promises and debounce are what front-end bugs are made of. They do not test components or CSS.
Can candidates answer in TypeScript?
Yes. Ask them to add types to the starter as they go. The questions and the expected output stay the same.
Why do some snippets print nothing or throw before the candidate starts?
The function bodies are empty on purpose. A stub that returns nothing prints undefined, or throws when it is called as a function. Reading that first error is a reasonable first step.

Read next

Try it in a pad2 free interviews, no card needed.