Skip to content
Tutorials Center
My learning

Topics

Lesson 152 of 156 ยท Practice and Review

JavaScript Interview Questions

37 common JavaScript interview questions with clear, accurate answers, grouped by level from junior to senior, plus live this-context and output-prediction puzzles to run.

Technical interviews for front-end and full-stack roles almost always include JavaScript questions. Some check vocabulary ("what is a closure?"), some test whether you can predict what code prints, and some ask you to reason about trade-offs. This page collects 37 of the most common questions, grouped by level (Junior, Mid and Senior) and by topic.

Each answer is hidden. Read the question, answer it out loud as if the interviewer were in front of you, and only then open the answer to compare. Interviewers care less about textbook definitions than about whether you can explain an idea simply and back it up with a small example. The code-reading questions come with a live editor: predict the output first, then press Run.

A good answer has three parts: a one-sentence definition, a tiny example, and one practical consequence ("โ€ฆso in loops, use let"). Practice saying all three in under a minute.

Junior level

Variables and types

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

var is function-scoped, can be redeclared, and is hoisted with the value undefined. let and const are block-scoped (they live inside the nearest { }) and can't be used before their declaration line. const also prevents reassignment, but it does not make objects immutable: you can still push to a const array. Modern code uses const by default, let when the value must change, and avoids var. See Variables.

2. What is the difference between == and ===?

=== (strict equality) compares without converting types: different types are never equal. == (loose equality) converts the operands first, following rules that produce surprises such as 0 == "" and [] == false both being true. Use === everywhere. The one common exception is value == null, which is a short way to check for both null and undefined. See Comparison.

3. What are the primitive types in JavaScript?

There are seven: string, number, bigint, boolean, undefined, null and symbol. Everything else is an object (including arrays, functions, dates and maps). Primitives are immutable and compared by value; objects are compared by reference, so {} === {} is false. See Data Types.

4. What is the difference between null and undefined?

undefined means "no value was ever assigned": an uninitialized variable, a missing property, a missing argument, or a function with no return. null is a value you assign on purpose to mean "intentionally empty". typeof undefined is "undefined", while typeof null is "object" because of a historic bug. See null and undefined.

5. Which values are falsy?

false, 0, -0, 0n, "" (empty string), null, undefined and NaN. Everything else is truthy, including "0", "false", [] and {}. This matters for defaults: count || 10 replaces a real 0 with 10, which is why ?? (nullish coalescing) exists. See Booleans.

6. What is NaN and how do you check for it?

NaN ("not a number") is the result of a failed numeric operation, such as Number("abc") or 0 / 0. Its type is still "number", and it is the only value not equal to itself, so x === NaN is always false. Check with Number.isNaN(x). Avoid the global isNaN(), which converts its argument first, so isNaN("hello") returns true. See Numbers.

7. How do you check whether a value is an array?

Use Array.isArray(value). typeof [] returns "object", so typeof can't tell arrays apart from other objects. value instanceof Array usually works too, but fails for arrays created in another window or iframe, which Array.isArray() handles correctly.

Functions and scope

8. What is hoisting?

Before running code in a scope, JavaScript sets up all the declarations in it. Function declarations are fully hoisted, so you can call them before the line where they appear. var variables are hoisted and initialized to undefined. let, const and class are hoisted too, but stay uninitialized in the temporal dead zone until their line runs; touching them earlier throws a ReferenceError. See Scope and Hoisting.

9. Function declaration, function expression and arrow function: what's the difference?

A declaration (function f() {}) is hoisted and has its own this. An expression (const f = function () {}) is created when that line runs, so it can't be called earlier. An arrow function (const f = () => {}) is also an expression, but it has no own this, arguments or prototype, takes this from the surrounding code, and can't be used with new. Arrows are ideal for callbacks; regular functions for methods that need their own this. See Arrow Functions.

10. What is a closure?

A closure is a function together with the variables it captured from the scope where it was created. The function keeps access to those variables even after the outer function has returned. Closures give you private state (counters, caches), and they are how callbacks remember their context. Example: function makeId() { let n = 0; return () => ++n; }; each call to the returned function sees the same n. See Closures.

Code reading: what does this print, and why?

JS Question 11: timers in a loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

11. Why does the var loop print 4 three times?

var creates one i for the whole function, and the callbacks run after the loop has finished, when i is already 4. All three closures share that variable. let creates a new binding for every iteration, so each callback captures its own j, printing 1, 2 and 3. The fix for old code is simply to switch to let.

12. What do the rest and spread syntaxes do?

Both use ..., but in opposite directions. Rest collects many values into one array or object: function sum(...nums) or const { id, ...others } = user. Spread expands one iterable or object into many values: Math.max(...nums), [...a, ...b], { ...defaults, ...options }. Object spread makes a shallow copy. See Spread and Rest.

Arrays and objects

13. What is the difference between map() and forEach()?

map() returns a new array made of the callback's return values, so you use it to transform data. forEach() returns undefined and is only for side effects, like logging or updating the DOM. Neither changes the original array by itself, and neither can be stopped early; use for...of with break, or some()/find(), when you need to stop. See Iterating Arrays.

14. How do you copy an object, and what is a shallow copy?

{ ...obj } and Object.assign({}, obj) make a shallow copy: the top level is new, but nested objects and arrays are still shared with the original. For a deep copy, use structuredClone(obj), which copies nested data, dates, maps and sets (but not functions or class prototypes). JSON.parse(JSON.stringify(obj)) is an older trick that loses dates, undefined and more. See Copying Objects.

15. Which array methods change the original array?

push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin mutate the array. map, filter, slice, concat, flat and the ES2023 methods toSorted, toReversed, toSpliced and with return new arrays. Mutating shared data is a common bug source, especially with sort() on arrays that came from elsewhere. See Array Methods.

Mid level

this, prototypes and classes

16. How is the value of this decided?

For regular functions, this depends on how the function is called, not where it is written. As a method (obj.f()), this is obj. As a plain call (f()), it is undefined in strict mode (and in modules and classes), or the global object in sloppy mode. With new, it is the new instance. call, apply and bind set it explicitly. Arrow functions have no own this; they use the this of the code around them. See The this Keyword.

Code reading: predict both lines.

JS Question 17: this in callbacks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

17. Why does the regular callback lose the team name?

map() calls the regular callback as a plain function, so it gets its own this, which is undefined in strict code such as this module (in an old sloppy-mode script it would be the global object). The ?. avoids a crash and prints undefined instead of the name. The arrow callback has no this of its own, so it uses the this of listArrow, which is team. That is why arrow functions are the default choice for callbacks inside methods.

18. What is the prototype chain?

Every object has a hidden link to another object, its prototype. When you read a property that the object doesn't have, JavaScript looks at the prototype, then the prototype's prototype, and so on until it reaches null. That is how arrays get map() from Array.prototype and how class instances share methods. Writing a property always creates it on the object itself, never on the prototype. See Prototypes.

19. Are JavaScript classes real classes?

They are mostly syntax over prototypes. class creates a constructor function, puts methods on its prototype, and wires up inheritance with extends. But classes add real features too: they must be called with new, their bodies are always strict, methods are non-enumerable, and they support truly private #fields and static blocks that old constructor functions can't express. See Classes.

20. What is the difference between call, apply and bind?

All three set this explicitly. call(thisArg, a, b) calls the function immediately with arguments listed one by one. apply(thisArg, [a, b]) calls it immediately with arguments in an array. bind(thisArg, a) does not call the function; it returns a new function with this (and optionally the first arguments) permanently fixed, which is useful for callbacks. See call, apply and bind.

21. What does strict mode change?

Strict mode turns silent mistakes into errors and removes confusing features. Assigning to an undeclared variable throws instead of creating a global, this in plain function calls is undefined instead of the global object, writing to read-only properties throws, duplicate parameter names are errors, and with is banned. Modules and class bodies are always strict, so most modern code already runs in strict mode. See Strict Mode.

Asynchronous JavaScript

22. What is the event loop?

JavaScript runs your code on a single thread with one call stack. Slow work such as timers, network requests and user input is handled by the browser or Node.js, which queue a callback when the work is done. The event loop waits until the call stack is empty, runs all pending microtasks (promise callbacks, queueMicrotask), lets the browser render if needed, then takes the next macrotask (a timer, an event) and repeats. See Asynchronous JavaScript.

Code reading: in what order do the letters appear?

JS Question 23: event loop order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

23. Why is the order A, E, G, C, F, D, B?

Synchronous code runs first: A, then the async function's body up to its first await (E), then G. Next the microtask queue empties in order: C was queued first, then the continuation after await null (F). Running C queued its .then callback D at the back of the microtask queue, so D comes after F. Only when microtasks are exhausted does the timer macrotask run: B.

24. What are the states of a promise?

A promise starts pending, then settles exactly once into either fulfilled (with a value) or rejected (with a reason). Once settled, it never changes. then() registers callbacks and returns a new promise, which is what makes chaining work; returning a value from a callback fulfills the next promise, and throwing rejects it. See Promises.

25. How do you handle errors with async/await, and when do you use Promise.all versus Promise.allSettled?

Wrap await calls in try...catch, or call .catch() on the promise the async function returns. Remember that fetch() only rejects on network failures, so also check response.ok. Use Promise.all() when every result is required: it rejects as soon as one promise rejects. Use Promise.allSettled() when you want every outcome, for example loading several independent widgets where one failure shouldn't hide the others. See Async and Await and Promise Combinators.

26. What is the difference between debounce and throttle?

Both limit how often a function runs during a burst of events. Debounce waits until the events stop for a set time, then runs once: ideal for search-as-you-type or saving a draft. Throttle runs at most once per interval while events keep coming: ideal for scroll or resize handlers that should update regularly. A minimal debounce:

JavaScript
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

The DOM and the browser

27. What is event bubbling, and what is event delegation?

Most events fire on the target element, then bubble up through each ancestor to document (after an earlier capturing phase going down). Event delegation uses bubbling: you put one listener on a parent and use event.target.closest(selector) to find which child was clicked. It saves memory with long lists and automatically works for children added later. See Event Delegation.

28. What is the difference between preventDefault() and stopPropagation()?

preventDefault() cancels the browser's default action, such as following a link or submitting a form; the event still bubbles. stopPropagation() stops the event from reaching other elements further along its path; the default action still happens. They solve different problems, and you rarely need stopPropagation(), which can break delegated listeners elsewhere. See Events.

29. How do localStorage, sessionStorage and cookies differ?

localStorage keeps strings per origin until removed, roughly 5 MB, and is never sent to the server. sessionStorage has the same API but lasts only for one tab's session. Cookies are small (about 4 KB), are sent to the server with every matching request, can expire, and can be marked HttpOnly so JavaScript can't read them, which is why session tokens belong in cookies, not in web storage. See Web Storage.

30. What is the difference between a Map and a plain object?

A Map accepts any value as a key (objects, functions, numbers), keeps insertion order, has a size property, is directly iterable, and has no inherited keys like toString to collide with. It is also optimized for frequent additions and removals. Plain objects are better for fixed, known string keys (a record such as a user), and they convert directly to JSON. See Maps.

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

ES modules (import/export) are the standard: they work in browsers and Node.js, are always strict, load asynchronously, and their imports are static, so tools can analyze them and remove unused code (tree shaking). Top-level await is allowed. CommonJS (require/module.exports) is Node.js's original system: synchronous, dynamic, and not supported natively in browsers. New code should use ES modules. See Modules.

Senior level

Engine, memory and performance

32. How does garbage collection work, and what causes memory leaks?

Engines use reachability: anything that can be reached from the roots (global object, current call stack) is kept, and everything else is eventually freed by a mark-and-sweep style collector, so cycles are not a problem. Leaks happen when you keep references you no longer need: event listeners that are never removed, timers that are never cleared, growing caches or arrays, closures holding large data, and detached DOM nodes still referenced from JavaScript. WeakMap, AbortController signals for listeners and clearing timers are the usual fixes.

33. How would you find and fix a slow page?

Measure first: use the browser's Performance panel and performance.now() to find long tasks, rather than guessing. Common fixes are: avoid layout thrashing (reading layout properties like offsetHeight between DOM writes; batch reads, then writes), update the DOM in one go (a DocumentFragment or a single replaceChildren()), debounce expensive handlers, lazy-load code with dynamic import(), use the right data structure (a Set instead of includes() in a loop), and move heavy computation into a Web Worker.

34. Is JavaScript single-threaded? How do you get parallelism?

Your code on a page runs on one main thread, so a long loop blocks rendering and input. Concurrency comes from the event loop: many operations are in progress while the thread handles other callbacks. True parallelism needs Web Workers (or worker threads in Node.js), which run scripts on separate threads and communicate by message passing (postMessage), with data copied or transferred. SharedArrayBuffer and Atomics allow shared memory but require cross-origin isolation.

35. What are iterators and generators, and when are they useful?

An iterable is any object with a [Symbol.iterator]() method that returns an iterator: an object whose next() returns { value, done }. for...of, spread and destructuring all use this protocol. A generator (function*) is the easiest way to write one: each yield pauses the function and hands out a value. They are useful for lazy sequences (computing values only when needed), infinite streams, custom tree traversals, and making your own classes work with for...of. See Iterators and Generators.

36. What are WeakMap and Proxy used for?

A WeakMap holds its keys weakly: if nothing else references a key object, the entry can be garbage-collected. It is ideal for attaching private data or cached results to objects (such as DOM nodes) without causing leaks; the trade-off is that it isn't iterable and has no size. A Proxy wraps an object and intercepts operations such as get, set and delete through traps, which powers validation layers, change tracking and the reactivity systems of front-end frameworks. See Proxy and Reflect.

Security

37. What is XSS, and how do you prevent it in JavaScript?

Cross-site scripting (XSS) happens when attacker-controlled text is inserted into a page as code, for example with element.innerHTML = userComment, letting it run scripts with your users' sessions. Prevent it by treating user data as text: use textContent, setAttribute() with safe attributes and createElement() instead of building HTML strings; never pass user data to eval(), new Function() or string-based setTimeout(); validate URLs before using them in href (block javascript:); and add a Content Security Policy as a second layer of defense. Server-side escaping in templates matters just as much.

Practice: this contexts and output puzzles

Interviewers love short programs where the answer is not what a quick read suggests. The questions above explain the rules; this section drills them. For every snippet, write your prediction on paper before you press Run, then check the numbered lines against the explanation below it.

Where does this point?

The rule from question 16 applies everywhere: look at how the function is called, not where it is written. This table lists the situations that come up most often (assuming strict code, which includes modules and class bodies):

Situation Value of this
obj.method() obj
const f = obj.method; f() undefined (the link to obj is gone)
(obj.method)() obj (parentheses alone keep the reference)
(0, obj.method)() undefined (the comma operator returns a plain value)
a.b.method() a.b, the object directly before the final dot
A function nested inside a method undefined, unless it is an arrow function
An arrow function anywhere The this of the code around where it was written
A getter or setter The object you read or write the property on
new Fn() or new Class() The new instance
fn.call(x), fn.apply(x), fn.bind(x)() x (a bound function ignores later call)
array.map(fn, x) and similar x, if you pass the optional thisArg
Top level of an ES module undefined
Top level of a classic browser script window
Inline onclick="..." attribute The element
A listener added with addEventListener (regular function) The element, same as event.currentTarget
A regular function passed to setTimeout window in browsers, a Timeout object in Node.js
JS Puzzle 1: predict every line

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Explanations for puzzle 1
  • 1, 3, 8, 9: each call has an object right before the last dot (or call names one), so this is that object. Line 8 shows that only the last object counts: who() sees profile, not user.
  • 2, 4: extracted() and (0, user.regular)() are plain calls. The function no longer remembers user, so this is undefined in strict code and this?.name gives undefined. In a sloppy-mode script it would be window, and window.name is an empty string by default.
  • 5: an arrow function does not get this from the object literal (object literals are not scopes). It uses the top level of the module, where this is undefined.
  • 6: a getter runs with this set to the object you read it from.
  • 7: inner() is a plain call, so its this is undefined. arrowInner borrows this from nested(), which is user.
  • 10: bind creates a function whose this is fixed forever; a later call cannot override it.
  • 11, 12: incArrow is a class field holding an arrow function, created per instance, so this is the instance even when destructured. inc lives on the prototype, loses its object when pulled out, and throws a TypeError when it tries to read this.count of undefined.
  • 13, 14: a plain call of a regular function in a module gives undefined; an arrow at module level gives the module's this, also undefined.
  • 15: the second argument of map() is the this for the callback.

Output prediction

The next puzzles mix type coercion, references and default values. They are classic because each one hides a single rule: object keys are strings, + prefers strings, objects are compared by reference, and arguments are passed by sharing a reference (see Pass by Value and Pass by Sharing).

JS Puzzle 2: coercion and equality

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Explanations for puzzle 2
  • Objects as keys: property keys are always strings (or symbols). Both b and c turn into "[object Object]", so the second assignment overwrites the first: 456 is printed for a[b], and there is only one key. Use a Map when you need real objects as keys.
  • 3 + 2 + "7" evaluates left to right: 5, then string concatenation gives "57". "7" + 3 + 2 is a string from the start, so "732". The - operator always means numbers, so "7" - 2 is 5 and the last step gives "51".
  • [] + [] is an empty string (both arrays become ""), which is why one output line looks blank; [] + {} is "[object Object]". "b" + "a" + +"a" + "a" contains +"a", which is NaN, hence "baNaNa".
  • [1, 2] == [1, 2] compares two different objects, so false. Against the string "1,2" the array is converted to a string first, so it is true.
  • null: == treats null as equal only to undefined, so null == 0 is false. The relational operators >= and > convert null to 0, giving true and false.
  • NaN is not equal to itself; Object.is() and Number.isNaN() can detect it. Floating-point sums such as 0.1 + 0.2 need a tolerance, not ===.
  • typeof null is the historic "object", and NaN is a number.
  • sort() without a comparator sorts by string, so 10 comes before 9.
  • map(parseInt) passes (value, index), and parseInt treats the index as the radix: parseInt("2", 1) and parseInt("3", 2) are NaN.
  • Math.max() with no arguments is -Infinity, the identity for "largest so far".
  • Spread over a string walks code points, so the emoji counts as one item, while .length counts UTF-16 units and says 3.
  • !!"false" is true (a non-empty string), and [] == false is true after both sides convert to 0, even though [] itself is truthy.
JS Puzzle 3: references, defaults and hoisting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Explanations for puzzle 3
  • Setting the variable to null only removes that one reference. The array still holds the object, so the list is unchanged. Memory is freed only when nothing refers to the object.
  • A spread copy is shallow: the new array is separate (pushing to copy does not change team), but its elements are the same objects, so changing copy[0].n changes team[0].n.
  • Default values are evaluated on every call. Each call to addTo gets a fresh []; the results are ["a"] and ["b"]. (Python programmers: this is different from Python's shared default list.)
  • Defaults can use earlier parameters. h = w * 2 sees the w that was just resolved, so area({ w: 3 }) is 3 * 6 = 18. The = {} lets you call area() with no argument at all.
  • undefined triggers a default, null does not. f(1, null, 5) keeps null. f.length is 1 because only the parameters before the first default are counted, and the rest parameter is skipped.
  • Parameters hold copies of references. Changing n inside change doesn't touch the caller's number. Mutating o through the reference is visible outside; reassigning o or arr only changes the local name.
  • var in a loop shares one binding, so every closure reads the final 3.
  • Hoisting: the function declaration is available before its line, while var notYet exists but is still undefined at that point, so typeof notYet is "undefined".
  • Objects are compared by identity. x and y are one object; two separate literals are never ===.

More on the rules behind these puzzles: The this Keyword, Type Conversion, Comparison, Closures and Parameters.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. let and const are hoisted, yet using them before their declaration throws. What is that period called?

    The binding exists from the start of the block but stays uninitialized until its declaration runs. Accessing it in between throws a ReferenceError.
  2. 2. Which statement about microtasks and macrotasks is correct?

    After the call stack empties, the event loop drains the entire microtask queue, including microtasks queued while draining, before taking the next timer or event.
  3. 3. Why is element.innerHTML = userInput dangerous?

    Markup such as <img onerror> in user input becomes live HTML. textContent always treats the input as plain text.
  4. 4. When is Promise.allSettled() a better choice than Promise.all()?

    Promise.all() rejects on the first failure. Promise.allSettled() waits for all of them and reports each as fulfilled or rejected.

Summary

  • Junior questions check fundamentals: let/const/var, ===, types, falsy values, hoisting, closures and array methods.
  • Mid-level questions focus on this, prototypes and classes, the event loop, promises, events and storage.
  • Senior questions add memory, performance, threads and workers, iterators, WeakMap/Proxy and security.
  • For code-reading questions, trace synchronous code first, then microtasks, then macrotasks, and watch for shared var bindings.
  • For this puzzles, find the call site: the object before the last dot, new, call/bind, or nothing at all. Arrows borrow this from the code around them.
  • For output puzzles, look for the one hidden rule: keys become strings, + prefers strings, objects compare by reference, undefined triggers defaults and null does not.
  • Answer with a definition, a tiny example and a practical consequence, and practice saying it out loud.

You've reached the end of the JavaScript course. Use the cheat sheet for quick review, keep sharpening your skills with the practice exercises, and go back to the JavaScript course overview whenever you want to revisit a topic.