Data types

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? console.log(typeof undefined);

    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.

    Data types explained

    JavaScript values are either primitives, which hold one simple value, or objects, which hold named properties. The typeof operator reports which kind a value is.

    There are seven primitive types: string, number, bigint, boolean, undefined, symbol and null. Arrays and functions are objects. Every number, whole or fractional, uses the same 64-bit floating-point format, so decimal fractions such as 0.1 cannot be stored exactly and small rounding errors appear. Comparing with a small tolerance, such as Number.EPSILON for values near 1, avoids the problem.

    console.log(typeof 42);
    console.log(typeof "hi");
    console.log(typeof undefined);
    console.log(typeof null);
    console.log(typeof [1, 2]);
    

    Caveat: typeof null returns "object", a long-standing mistake in the language that cannot be changed without breaking existing code. Test for null with ===.

    Worked example

    The sum 0.1 + 0.2 is stored as about 0.30000000000000004, so the difference from 0.3 is about 5.55×10−175.55 \times 10^{-17}. Number.EPSILON is about 2.22×10−162.22 \times 10^{-16}, which is larger, so Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON is true and the two values count as equal.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this JavaScript code log?

      console.log(typeof true);

      • int
      • logical
      • boolean
      • bool
    • Medium

      How many values in this array does the filter keep?

      const values = [() => 1, null, NaN, "5", undefined]; console.log(values.filter((v) => typeof v === "object").length);

    • Hard

      How many values in this array does the filter keep?

      const values = [[], NaN, new Number(4), 7, -0, 0.1 + 0.2]; console.log(values.filter((v) => typeof v === "number").length);