JavaScript Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 1. How many data types does JavaScript have according to the specification?

    Correct answer: 8: seven primitives and object

    Primitives: number, bigint, string, boolean, null, undefined, symbol. Everything else is object, including arrays, functions and dates. Functions are objects, even though typeof returns 'function' for them.

  2. 2. What does typeof null return?

    Correct answer: 'object'

    It's a historical bug from the language's first implementation, kept for compatibility. null is a separate primitive. Check for it with strict equality: value === null.

  3. 3. What does typeof NaN return?

    Correct answer: 'number'

    NaN (Not-a-Number) is a special value of the number type, the result of an invalid math operation such as 0 / 0 or Number('abc'). Check for it with Number.isNaN(x).

  4. 4. How does let differ from var?

    Correct answer: let is scoped to a {} block, var to a function

    A var declared inside an if or for is visible throughout the function. Also, var is hoisted with the value undefined and becomes a window property at the top level, while let and const are in the "temporal dead zone" until declared.

  5. 5. What happens?

    const user = { name: "Ann" };
    user.name = "Bob";

    Correct answer: It works: const forbids reassignment, not mutation of the object

    const fixes the reference: user = {} throws, but the object's contents can change. To prevent property changes, use Object.freeze (shallowly).

  6. 6. What does this code print?

    console.log(x);
    var x = 5;

    Correct answer: undefined

    The var declaration is hoisted to the top of the function and initialized with undefined, while the assignment stays in place. With let or const this would be a ReferenceError.

  7. 7. What does this code print?

    console.log(y);
    let y = 5;

    Correct answer: ReferenceError

    let and const are hoisted too, but until the declaration line they're in the temporal dead zone (TDZ): any access throws a ReferenceError. This helps catch variables used before initialization.

  8. 8. How does == differ from ===?

    Correct answer: == coerces types before comparing, === compares without coercion

    0 == '' and '1' == 1 are true because of coercion, but false with ===. Loose equality rules are confusing, so === is almost always used. A handy exception: x == null checks for both null and undefined at once.

  9. 9. How does null differ from undefined?

    Correct answer: undefined means no value was assigned, null is an explicit "empty" set by the programmer

    undefined is what uninitialized variables, missing properties and parameters, and functions without return produce. null is assigned on purpose. null == undefined is true, but null === undefined is false.

  10. 10. What does NaN === NaN return?

    Correct answer: false

    NaN is not equal to anything, not even itself. Use Number.isNaN(x) or Object.is(x, NaN) to check. The global isNaN('abc') coerces its argument to a number first and returns true for strings.

  11. 11. What does 0.1 + 0.2 === 0.3 evaluate to?

    Correct answer: false

    Numbers are stored in binary IEEE-754 format, and 0.1 and 0.2 can't be represented exactly - the sum is 0.30000000000000004. Compare numbers with a tolerance (Math.abs(a - b) < Number.EPSILON), and handle money as integer cents.

  12. 12. What are '5' + 3 and '5' - 3?

    Correct answer: '53' and 2

    If one operand of + is a string, concatenation happens. Other arithmetic operators convert operands to numbers. That's why values from input.value are converted with Number() before adding.

  13. 13. Which of these values is falsy?

    Correct answer: 0

    Falsy values: false, 0, -0, 0n, '', null, undefined, NaN. Everything else is truthy, including the string '0', an empty array [] and an empty object {}.

  14. 14. How does count || 10 differ from count ?? 10 when count = 0?

    Correct answer: || returns 10, while ?? returns 0

    || substitutes the fallback for any falsy value, while ?? only does so for null and undefined. For numbers and strings where 0 and '' are valid values, ?? is the right choice.

  15. 15. What does user?.address?.city return if user = {}?

    Correct answer: undefined

    Optional chaining short-circuits and returns undefined if the value on the left is null or undefined. Without ?., user.address.city would throw a TypeError. There are also forms for calls fn?.() and indexes arr?.[0].

  16. 16. How does an arrow function differ from a regular one?

    Correct answer: It has no own this or arguments and can't be called with new

    An arrow takes this from the scope where it was created, which makes it handy for callbacks inside methods. But it doesn't work as an object method: this won't point to the object. Only function declarations are fully hoisted.

  17. 17. Can you call a function before its declaration?

    greet();
    function greet() { console.log("hi"); }

    Correct answer: Yes: a function declaration is fully hoisted

    Function declarations are created before code in their scope runs. With a function expression (const greet = function () {}), calling before the declaration fails: the variable is in the TDZ (or undefined with var).

  18. 18. What does this code print?

    function makeCounter() {
      let count = 0;
      return () => ++count;
    }
    const c = makeCounter();
    c(); c();
    console.log(c());

    Correct answer: 3

    This is a closure: the returned function remembers the count variable from the scope where it was created, and each call increments it. Calling makeCounter() again would create an independent counter.

  19. 19. What is a closure?

    Correct answer: A function together with access to variables of the outer scope where it was created

    Every JS function remembers the lexical environment where it was created and can read and change its variables even after the outer function finishes. Private data, function factories, memoization and event handlers are built on this.

  20. 20. What does this code print?

    const a = { n: 1 };
    const b = a;
    b.n = 2;
    console.log(a.n);

    Correct answer: 2

    Objects are passed by reference: b points to the same object as a. To get a copy, use spread { ...a } (shallow) or structuredClone(a) (deep).

  21. 21. What does const copy = { ...original } do?

    Correct answer: A shallow copy: nested objects remain shared

    Spread copies only own first-level properties. If original.address is an object, it's shared by both copies. structuredClone gives a deep copy, but it doesn't copy functions or DOM nodes.

  22. 22. What does [1, 2, 3].map(x => x * 2) return?

    Correct answer: [2, 4, 6]

    map creates a new array from the callback's results without changing the original. Similar non-mutating methods: filter (selection), reduce (folding into one value), find, some, every.

  23. 23. What does [1, 2, 3].forEach(x => x * 2) return?

    Correct answer: undefined

    forEach is for side effects and always returns undefined. Use map to get a new array. Another difference: you can't break out of forEach - use for...of, some or find for that.

  24. 24. What does [1, 2, 3, 4].reduce((sum, x) => sum + x, 0) return?

    Correct answer: 10

    reduce walks the array, passing the accumulator from step to step; the second argument is the initial value. Without it, the first element becomes the initial accumulator, and an empty array throws a TypeError.

  25. 25. How does for...in differ from for...of?

    Correct answer: for...in iterates over object keys, for...of over values of an iterable

    for (const key in obj) goes over enumerable string keys, including inherited ones. for (const item of arr) works with iterables: arrays, strings, Map, Set. for...in isn't suitable for arrays - it yields indexes as strings.

  26. 26. How does slice differ from splice?

    Correct answer: slice returns part of the array without changes, splice mutates the original

    arr.slice(1, 3) creates a new array. arr.splice(1, 2, 'x') removes and inserts elements in arr itself. The non-mutating alternative is toSpliced(). Other mutating methods: push, pop, shift, sort, reverse.

  27. 27. What do [NaN].includes(NaN) and [NaN].indexOf(NaN) return?

    Correct answer: true and -1

    indexOf uses strict equality ===, and NaN !== NaN. includes uses the SameValueZero algorithm, which treats NaN as equal to itself. So includes is more reliable for checking presence.

  28. 28. What does this code print?

    const { name = "Guest", age } = { age: 30 };
    console.log(name, age);

    Correct answer: Guest 30

    Destructuring extracts properties into variables, and the default value is used when the property is undefined. You can rename ({ name: userName }) and destructure nested objects and arrays.

  29. 29. What does sum(1, 2, 3) return?

    function sum(...nums) {
      return nums.length;
    }

    Correct answer: 3

    A rest parameter collects the remaining arguments into a real array. Unlike the legacy arguments, it's an array with map and reduce, and it works in arrow functions.

  30. 30. What does Math.max(...[3, 7, 2]) return?

    Correct answer: 7

    Spread "expands" the array into separate arguments: Math.max(3, 7, 2). Without spread, Math.max([3, 7, 2]) returns NaN. Spread is also used to copy and merge arrays and objects.

  31. 31. What does JSON.stringify({ a: 1, b: undefined, c: () => 1 }) return?

    Correct answer: '{"a":1}'

    Properties whose values are undefined, functions or symbols are skipped (in arrays they become null). Date becomes a string, Map and Set become {}. Circular references throw an error.

  32. 32. In what order are the numbers printed?

    console.log(1);
    setTimeout(() => console.log(2), 0);
    Promise.resolve().then(() => console.log(3));
    console.log(4);

    Correct answer: 1 4 3 2

    Synchronous code runs first (1, 4). Then the event loop runs all microtasks - promise callbacks (3) - and only then the next macrotask - the timer (2). setTimeout(fn, 0) doesn't mean "immediately".

  33. 33. Which states can a promise be in?

    Correct answer: pending, then fulfilled or rejected - and it never changes again

    A promise starts pending and settles exactly once into fulfilled or rejected. Further resolve/reject calls are ignored. A promise can't be cancelled - use AbortController to cancel operations.

  34. 34. What does an async function return?

    Correct answer: Always a promise, even with return 42 inside

    async function f() { return 42 } returns Promise<42>. An exception inside becomes a rejected promise. That's why the result is obtained with await or .then().

  35. 35. Why won't catch catch the error?

    try {
      fetch("/api").then(r => { throw new Error("fail"); });
    } catch (e) {
      console.log("caught");
    }

    Correct answer: The error happens later, after try has already finished

    The try block ran synchronously and finished before the server responded. Errors in the chain are caught with .catch(), or by writing await fetch(...) inside try in an async function - then catch works.

  36. 36. What does const arr = ['a', 'b']; console.log(arr[20]); print?

    Correct answer: undefined

    Accessing a nonexistent index, like a missing object property, returns undefined without an error. For the last element, arr.at(-1) is handy.

  37. 37. What does this code print?

    const s = "hello";
    s[0] = "H";
    console.log(s);

    Correct answer: hello

    Strings are immutable: you can't change a character; the assignment is silently ignored (a TypeError in strict mode). You need to create a new string: s[0].toUpperCase() + s.slice(1).

  38. 38. How do you reliably check that a value is an array?

    Correct answer: Array.isArray(value)

    typeof [] returns 'object', and strings and array-like objects also have length. Array.isArray works even for arrays from other iframes, where instanceof Array fails.

  39. 39. Why is textContent safer than innerHTML for displaying user text?

    Correct answer: It inserts text as is, without parsing HTML - XSS is impossible

    el.innerHTML = userInput parses the string as markup, and <img src=x onerror=alert(1)> runs a script. textContent shows tags as text. If you really need HTML, clean it with a sanitizer (DOMPurify).

  40. 40. Why is addEventListener better than el.onclick = handler?

    Correct answer: It allows multiple handlers and options (once, passive)

    Reassigning onclick overwrites the previous handler. addEventListener adds them independently and supports the capture phase (capture), one-time handlers and removal via signal (AbortController). Remove handlers with removeEventListener and the same function.

  41. 41. What does event.preventDefault() do?

    Correct answer: Cancels the browser's default action (navigation, form submission)

    For example, a link won't follow its href, a form won't submit, a checkbox won't toggle. Stopping bubbling is event.stopPropagation(); they're different things and often confused.

  42. 42. What is event bubbling?

    Correct answer: The event fires on the element and then rises through its ancestors up to document

    A click on a button inside a div triggers the button's handlers, then the div's, then higher. Before bubbling there's the capturing phase - from window down to the target. event.target is where the event happened, event.currentTarget is whose handler is running now.

  43. 43. What is event delegation about?

    Correct answer: One handler on a parent handles children's events via event.target

    Instead of 1000 handlers on every table row, there's one on table that finds the target via event.target.closest('tr'). This saves memory and automatically works for elements added later. It relies on bubbling.

  44. 44. How does localStorage differ from sessionStorage?

    Correct answer: localStorage persists indefinitely, sessionStorage until the tab is closed

    Both store strings per origin, a few megabytes in size, and aren't sent to the server (unlike cookies). sessionStorage is also isolated per tab. Storing tokens and secrets there is unsafe: any script on the page can read them.

  45. 45. What does localStorage.getItem('n') return after localStorage.setItem('n', 5)?

    Correct answer: '5'

    Web Storage stores only strings - the value is converted with String(). An object becomes '[object Object]', so complex data is saved with JSON.stringify and read with JSON.parse.

  46. 46. How does DOMContentLoaded differ from load?

    Correct answer: DOMContentLoaded - the DOM is built; load - images and styles are loaded too

    DOMContentLoaded is enough for working with the DOM (defer scripts run right before it). load waits for all resources, including images and iframes - you need it, for example, to measure image sizes.

  47. 47. How does Map differ from a plain object?

    Correct answer: Map keys can be any values, and insertion order is preserved

    Object keys are strings or symbols (the number 1 becomes '1'), and there are inherited properties. Map accepts objects as keys, has size and get/set/has/delete, and is convenient for frequent additions and removals.

  48. 48. How do you quickly remove duplicates from an array of primitives?

    Correct answer: [...new Set(arr)]

    Set stores only unique values (SameValueZero comparison). Spread turns it back into an array. Arrays of objects need a key: for example, a Map by id.

  49. 49. What does the 'use strict' directive give you?

    Correct answer: Strict mode: errors instead of silent failures

    For example, assigning to an undeclared variable throws instead of creating a global, and this in a regular function is undefined, not window. Modules and classes run in strict mode automatically.

  50. 50. How do you find the first element with the card class on the page?

    Correct answer: document.querySelector('.card')

    querySelector accepts any CSS selector and returns the first element or null. querySelectorAll returns a static NodeList of all matches. getElementsByClassName takes the class name without a dot, and indexing starts at 0.

  51. 51. Does this code throw an error?

    const user = { name: "Ann" };
    user.name = "Bob";

    Correct answer: No - const forbids reassignment, not object changes

    user = {} would throw a TypeError, but mutating properties is allowed. To make the object itself read-only, use Object.freeze (shallowly).

  52. 52. What does a template literal give you compared to string concatenation?

    const msg = `Hello, ${name}!
    You have ${count} new messages.`;

    Correct answer: Embedded ${...} expressions and multi-line strings

    Backtick strings evaluate any expression inside ${}. They don't escape anything, so building HTML from user input with them is still an XSS risk.

  53. 53. What does arr.length = 0 do?

    Correct answer: Removes all elements from the array in place

    Setting length truncates the array, and every reference to it sees the change. arr = [] instead points the variable at a new array.

  54. 54. What does [1, 2].push(3) return?

    Correct answer: 3 - the new array length

    push mutates the array and returns its new length, a common source of bugs like arr = arr.push(x). For an immutable version use [...arr, x].

  55. 55. How does find differ from filter?

    const users = [{ id: 1 }, { id: 2 }, { id: 2 }];

    Correct answer: find returns the first match; filter returns all matches

    users.find(u => u.id === 2) gives one object and stops early; users.filter(...) always scans the whole array. findIndex returns the index instead.

  56. 56. What is the difference between some and every?

    Correct answer: some needs one match; every needs all elements to match

    Both stop as soon as the result is known. On an empty array some returns false and every returns true.

  57. 57. What does this code print in a classic (non-strict) script?

    let s = "cat";
    s[0] = "b";
    console.log(s);

    Correct answer: cat

    Strings are immutable: index assignment is silently ignored (or throws in strict mode). Create a new string instead: "b" + s.slice(1).

  58. 58. What type does (1.005).toFixed(2) return?

    Correct answer: A string

    toFixed returns a formatted string, so price.toFixed(2) + 1 concatenates. Also, due to binary floating point, (1.005).toFixed(2) is "1.00", not "1.01".

  59. 59. What does greet() return?

    function greet(name = "guest") {
      return `Hi, ${name}`;
    }

    Correct answer: "Hi, guest"

    Default parameters apply when the argument is undefined (missing or passed explicitly). greet(null) gives "Hi, null", because null is a value.

  60. 60. What are title and year after this destructuring?

    const movie = { name: "Up" };
    const { name: title, year = 2009 } = movie;

    Correct answer: title is "Up", year is 2009

    name: title renames the variable, and = 2009 provides a default when the property is undefined.

  61. 61. What does [a, b] = [b, a] do?

    Correct answer: Swaps the values of a and b

    The right side creates a temporary array, then destructuring assigns its elements. If the previous line has no semicolon, it may be parsed as an index access - another reason to use semicolons or a linter.

  62. 62. How does "toString" in obj differ from Object.hasOwn(obj, "toString") for obj = {}?

    Correct answer: in is true, Object.hasOwn is false

    in checks the whole prototype chain. Object.hasOwn (a safer replacement for obj.hasOwnProperty) checks only the object itself.

  63. 63. What does 0 && "hello" evaluate to?

    Correct answer: 0

    && returns the first falsy operand or the last one. In JSX, {count && <Badge />} therefore renders 0 when count is 0.

  64. 64. Which case runs for x = "1"?

    switch (x) {
      case 1: console.log("number"); break;
      case "1": console.log("string"); break;
    }

    Correct answer: case "1" - switch compares with ===

    switch uses strict equality. Without break, execution falls through into the next case.

  65. 65. When does a finally block run?

    Correct answer: Always, even after a return or an exception

    It is the place for cleanup such as hiding a loader or closing a connection. A return inside finally overrides the earlier return value, so avoid it.

  66. 66. How does Number.isNaN("abc") differ from isNaN("abc")?

    Correct answer: Number.isNaN gives false, global isNaN gives true

    The global isNaN coerces its argument, which leads to surprises. Number.isNaN checks only for the actual NaN value.

  67. 67. What does Math.round(-2.5) return?

    Correct answer: -2

    Math.round rounds .5 towards +∞, so Math.round(2.5) is 3 and Math.round(-2.5) is -2. Use Math.trunc, Math.floor or Intl.NumberFormat when you need other rules.

  68. 68. What does a function return if it has no return statement?

    Correct answer: undefined

    Only arrow functions with a concise body (x => x * 2) return the expression implicitly. A block body x => { x * 2 } returns undefined.

  69. 69. Why does document.querySelectorAll("li").map(...) throw?

    Correct answer: It returns a NodeList, which has no map method

    A NodeList has forEach and is iterable, but lacks most array methods. It is also static: it doesn't update when the DOM changes.

  70. 70. What does el.classList.toggle("open") do?

    Correct answer: Adds the class if missing, removes it if present

    A second argument forces the state: toggle("open", isOpen). Using classList is safer than editing the className string by hand.

  71. 71. In a click handler attached to <ul>, how do event.target and event.currentTarget differ?

    Correct answer: target is the clicked element; currentTarget is the <ul>

    This difference is the basis of event delegation: one handler on the parent inspects event.target (often with closest()).

  72. 72. What happens with JSON.parse("{ name: 'Ann' }")?

    Correct answer: It throws a SyntaxError: JSON needs double quotes

    JSON is stricter than JS object literals: no single quotes, no trailing commas, no comments. Wrap parsing of untrusted data in try/catch.

  73. 73. What does [1, [2, [3]]].flat() return?

    Correct answer: [1, 2, [3]]

    By default flat flattens one level. Pass a depth (flat(2)) or Infinity to flatten completely. flatMap maps then flattens one level.

  74. 74. What is a callback?

    button.addEventListener("click", () => save());

    Correct answer: A function passed to be called later by other code

    Event handlers, setTimeout and array methods all take callbacks. Deeply nested async callbacks ("callback hell") led to promises and async/await.

  75. 75. What does ["a", "b", "c"].at(-1) return?

    Correct answer: "c"

    at accepts negative indices counting from the end, a cleaner alternative to arr[arr.length - 1]. arr[-1] just looks for a property named "-1".