Skip to main content
CodingMarble

Interview questions and cheat sheets

JavaScript Interview Questions and Answers

This page gives you eighteen JavaScript interview questions, grouped from fundamentals to trick questions, each with a precise answer you can say aloud in under a minute. Code examples are short enough to rewrite on a whiteboard.

By CodingMarble · Published · 5 min read

Two colleagues discussing ideas at a whiteboard
Photo: ThisisEngineering on Unsplash

How to use this list

Interviewers rarely want a recited definition. They want to hear that you know why a rule exists and can predict what a piece of code prints. For each question below, read the answer, then close the page and explain it again in your own words with a small example.

The questions are grouped into fundamentals, functions and objects, asynchronous code, arrays and copying, and browser-side questions, with a final section of trick questions that test whether you actually run code in your head.

Fundamentals: variables, types and equality

1. What is the difference between var, let and const?

var is function-scoped and can be redeclared; let and const are block-scoped and cannot be redeclared in the same scope. const prevents reassigning the binding but does not freeze the value, so a const object can still be mutated. Prefer const by default and let when you need to reassign.

2. What is hoisting, and what is the temporal dead zone?

Declarations are registered before code runs. A var is hoisted and initialised to undefined, so reading it early gives undefined. let and const are also hoisted but stay uninitialised until their line executes, and touching them in that window throws a ReferenceError. That window is the temporal dead zone. Function declarations are hoisted with their body, so you can call them before the line where they appear.

3. What is the difference between == and ===

=== compares value and type with no conversion. == converts operands first, so 0 == '' and '1' == 1 are both true, and null == undefined is true. The conversion rules are easy to misremember, which is why most teams lint for === and reserve == null as the one deliberate shortcut for 'null or undefined'.

4. Why does typeof null return 'object'?

It is a bug from the first version of the language that was kept to avoid breaking existing code. null is a primitive that represents an intentional empty value. To test for it, compare directly with value === null; typeof cannot distinguish it from objects.

Functions, this and prototypes

5. What is a closure?

A closure is a function that keeps access to the variables of the scope where it was created, even after that scope has finished. It is how you get private state without classes.

JavaScript
function makeCounter() {
  let count = 0;            // private to each counter
  return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), b()); // 1 2 1

6. How is this determined?

For ordinary functions, this depends on how the function is called, not where it is written. obj.method() sets this to obj; a plain call gives undefined in strict mode (or the global object otherwise); new creates a fresh object; call, apply and bind set it explicitly. Detaching a method, such as passing obj.method as a callback, loses the receiver.

7. How do arrow functions treat this?

Arrow functions have no this of their own; they use the this of the surrounding scope at the time they were defined. That makes them useful for callbacks inside methods, and wrong for object methods that need their own receiver. They also cannot be used with new and have no arguments object.

8. What is the prototype chain?

Every object has an internal link to another object, its prototype. When a property is not found on the object, the engine follows the link, then the next, until it reaches null. Class syntax is a cleaner way to set up the same chain: methods defined in a class live on the prototype and are shared by every instance.

Asynchronous JavaScript

9. Explain the event loop, microtasks and macrotasks.

JavaScript runs one piece of code at a time on the call stack. When the stack is empty, the event loop first drains the microtask queue (promise callbacks, queueMicrotask), then takes one macrotask (timers, I/O, UI events), and repeats. So a resolved promise callback always runs before a setTimeout of zero.

JavaScript
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// A D C B

10. What are the states of a promise, and how do Promise.all and Promise.allSettled differ?

A promise is pending, then either fulfilled or rejected, and it never changes after that. Promise.all resolves with every result or rejects as soon as one input rejects. Promise.allSettled always waits for all inputs and reports each outcome, which suits batch jobs where one failure should not hide the others.

11. How do you handle errors with async and await?

Wrap awaited calls in try and catch, or attach a catch to the returned promise. An async function always returns a promise, so an uncaught throw inside it becomes a rejection that the caller must handle. A common mistake is forgetting that fetch only rejects on network failure; check response.ok yourself for 404 or 500 responses.

Arrays, copying and modules

12. When do you use map, filter and reduce?

map transforms each item and returns an array of the same length. filter keeps items for which the callback returns true. reduce folds an array into one value, such as a sum or an object keyed by id. None of them mutate the original array, and chaining them is fine for readability unless the data set is very large.

JavaScript
const orders = [{ id: 1, qty: 2 }, { id: 2, qty: 0 }, { id: 3, qty: 5 }];
const total = orders
  .filter((o) => o.qty > 0)
  .reduce((sum, o) => sum + o.qty, 0);
console.log(total); // 7

13. What is the difference between a shallow and a deep copy?

A shallow copy, made with the spread operator or Object.assign, copies top-level properties but shares nested objects, so changing a nested value changes both copies. A deep copy duplicates nested structures too. structuredClone handles most data types, including dates and maps, but throws on functions; JSON.parse(JSON.stringify(x)) drops functions and undefined and turns dates into strings.

14. What is the difference between ES modules and CommonJS?

ES modules use import and export, are statically analysable, and load asynchronously, which lets bundlers remove unused exports. CommonJS uses require and module.exports and loads synchronously, and is still common in older Node.js code. In ES modules, imports are live bindings rather than copies of values.

Browser-side questions

15. What is event delegation?

Instead of attaching a listener to every child, you attach one to a common parent and inspect event.target. It works because most events bubble up the tree. It saves memory and handles elements added later, for example rows appended to a list.

JavaScript
document.querySelector("#todo-list").addEventListener("click", (e) => {
  const item = e.target.closest("li");
  if (item) item.classList.toggle("done");
});

16. What is debouncing?

Debouncing delays a function until a quiet period has passed since the last call, so typing in a search box triggers one request rather than one per keystroke. Throttling instead limits the function to at most one call per interval. Debounce suits search and resize end; throttle suits scroll handlers.

Trick questions

17. What does this loop print?

JavaScript
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j), 0);
// 3 3 3 then 0 1 2

var shares one binding across all iterations, and the callbacks run after the loop ends, when i is 3. let creates a fresh binding per iteration, so each callback closes over its own value.

18. What does [10, 9, 1].sort() return, and why does 0.1 + 0.2 not equal 0.3?

Without a comparator, sort converts items to strings and compares them, so the result is [1, 10, 9]. Pass (a, b) => a - b for numeric order. Numbers are 64-bit binary floating point, and 0.1 and 0.2 have no exact binary form, so their sum is 0.30000000000000004. Compare with a small tolerance, or work in whole units such as paise or cents.

Practice tip: run every snippet in the browser console before the interview and change one thing at a time to see what breaks.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.