Senior JavaScript Developer Interview Questions

Common senior JavaScript interview questions with short answers.

When interviewing for a senior JavaScript role you'll get fewer "what does this method do" questions and more "how does this actually work" questions. Here are the ones that come up most often, with the short answer I'd give and a bit of code to back it up.

What is the event loop?

JavaScript runs on a single thread. The event loop takes work from queues and runs it when the call stack is empty. Promise callbacks go into the microtask queue, and timers and events go into the task (macrotask) queue. All microtasks run before the next task.

What does this log?

console.log("1")
setTimeout(() => console.log("2"), 0)
Promise.resolve().then(() => console.log("3"))
queueMicrotask(() => console.log("4"))
console.log("5")
// 1, 5, 3, 4, 2

The synchronous logs run first, then the microtasks, then the setTimeout callback, even with a delay of 0.

What is a closure?

A closure is a function that remembers the variables from the scope it was created in, even after that scope has finished running.

function createCounter() {
let count = 0
return () => ++count
}
const counter = createCounter()
counter() // 1
counter() // 2

count isn't reachable from outside, but the returned function still has access to it. This is how you get private state without a class.

How does this work?

this is decided by how a function is called, not where it's written. Arrow functions don't have their own this and use the one from the surrounding scope.

const user = {
name: "Pam",
greet() {
return `Hi ${this.name}`
},
}
user.greet() // "Hi Pam"
const greet = user.greet
greet() // TypeError in strict mode, because this is undefined

I go deeper on this in What is "this" in JavaScript?.

What is prototypal inheritance?

Every object has a hidden link to another object, its prototype. When you read a property that doesn't exist on the object, JavaScript looks up the prototype chain until it finds it or hits null.

const animal = {
speak() {
return `${this.name} makes a sound`
},
}
const dog = Object.create(animal)
dog.name = "Rex"
dog.speak() // "Rex makes a sound"

Classes are mostly syntax on top of this. See What is Prototypal Inheritance in JavaScript? and What is a Class in JavaScript?.

What's the difference between == and ===?

=== compares value and type. == converts types first, which leads to surprises.

0 == "" // true
"1" == 1 // true
null == undefined // true
0 === "" // false

Use === by default. The one common exception is value == null, which checks for both null and undefined.

What is debouncing and throttling?

Both limit how often a function runs. Debouncing waits until calls stop for a set time, which is good for search inputs. Throttling runs at most once per interval, which is good for scroll and resize. I wrote up both in Debounce and Throttle Functions in JavaScript.

How do you handle errors with promises and async/await?

With async/await, wrap the awaited code in a try...catch. For several requests where one failing shouldn't sink the rest, use Promise.allSettled.

async function loadDashboard() {
try {
const res = await fetch("/api/user")
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return await res.json()
} catch (error) {
console.error(error)
return null
}
}
const results = await Promise.allSettled([fetchUser(), fetchPosts()])
// [{ status: "fulfilled", value: ... }, { status: "rejected", reason: ... }]

Note that fetch only rejects on network errors, so you need to check res.ok yourself. For running async work inside loops, see Looping Through Async Methods in JavaScript.

What causes memory leaks in JavaScript?

Anything that keeps a reference to something you no longer need: event listeners that are never removed, intervals that are never cleared, caches that grow forever and detached DOM nodes held in variables. An AbortController is a clean way to remove several listeners at once.

const controller = new AbortController()
window.addEventListener("resize", onResize, { signal: controller.signal })
window.addEventListener("scroll", onScroll, { signal: controller.signal })
// later, removes both listeners
controller.abort()

What's the difference between ES modules and CommonJS?

CommonJS (require and module.exports) is Node's original module system. It loads synchronously and exports are resolved at runtime. ES modules (import and export) are the standard. They're static, so bundlers can tree-shake unused code, and they support top-level await.

// CommonJS
const { format } = require("./utils")
module.exports = { run }
// ES modules
import { format } from "./utils.js"
export function run() {}

How do you copy objects without mutating them?

The spread operator makes a shallow copy, so nested objects are still shared. structuredClone makes a deep copy and handles things like Date, Map and Set.

const original = { name: "Jim", address: { city: "Scranton" } }
const shallow = { ...original }
shallow.address.city = "Stamford"
original.address.city // "Stamford"
const deep = structuredClone(original)
deep.address.city = "Nashua"
original.address.city // still "Stamford"

ES2023 also added non-mutating array methods like toSorted, toReversed and with. More on arrays in How to Clone an Array in JavaScript.

When would you use a Map or WeakMap over an object?

Use a Map when keys aren't strings, when you add and remove keys often, or when insertion order matters. A WeakMap only takes objects as keys and doesn't stop them from being garbage collected, which makes it good for attaching data to DOM nodes or objects you don't own.

const metadata = new WeakMap()
function track(element) {
metadata.set(element, { clicks: 0 })
}
// when element is removed and unreferenced, its entry can be collected

What is reflow and how do you avoid layout thrashing?

Reflow is when the browser recalculates the position and size of elements. Reading a layout property like offsetHeight right after changing styles forces the browser to do it immediately. Doing that in a loop is layout thrashing.

// Bad: read, write, read, write...
items.forEach((item) => {
item.style.height = `${container.offsetHeight}px`
})
// Better: read once, then write
const height = container.offsetHeight
items.forEach((item) => {
item.style.height = `${height}px`
})

Batch reads before writes, animate transform and opacity instead of width or top, and use requestAnimationFrame for visual updates.

A senior interview is less about memorizing answers and more about explaining the tradeoffs. If you can explain why, not just what, you're in good shape.

Have some feedback on this post? .