Common quirks & gotchas

Computer Science · JavaScript

Question 1 of 10

0

    What does typeof NaN return?

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Common quirks & gotchas explained

    JavaScript has several behaviours that surprise most newcomers, from the default sort order of arrays to how NaN compares. Knowing the common ones prevents many hard-to-find bugs.

    Array sort without a comparator converts elements to strings and compares them character by character, so numbers sort as text and 10 comes before 9. Pass a comparator such as (a, b) => a - b to sort numbers. sort also changes the array in place.

    console.log([10, 9, 1].sort());
    console.log([1, 2, 3].map(parseInt));
    

    map passes three arguments to its callback: the value, the index and the array. parseInt takes an optional radix as its second argument, so the index is used as the radix. Caveat: NaN is not equal to itself, so test with Number.isNaN, and typeof NaN is number.

    Other quirks: typeof null is object, 0.1 + 0.2 is not exactly 0.3, and var declarations are hoisted with the value undefined. Coercion also makes [] == false true, because both sides become 0.

    Worked example

    [10, 9, 1].sort() compares the strings "10", "9" and "1". In character order "1" < "10" < "9", so the result is [1, 10, 9], not [1, 9, 10]. [1, 2, 3].map(parseInt) calls parseInt with radixes 0, 1 and 2: the results are 1, NaN and NaN, because 3 is not a binary digit.

    What you will practise

    105 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • == vs === differs in:
    • typeof null returns:
    • NaN is:
    • Hoisting means:
    • 0.1 + 0.2:
    • What does [] + [] evaluate to in JavaScript?
    • What does Number('') return?
    • Which of these values is falsy in JavaScript?

    …and 97 more.