CodeBlanks Logo Icon CodeBlanks

The typeof operator

JavaScript course · Beginner · Lesson 5/133

Learn how to check a variable's type with typeof and its pitfalls.

What is the typeof operator?

To find out a value's type you use the typeof operator. typeof returns the type of the value on its right as a string: "number", "string", "boolean" and so on.

For example, typeof 42 gives "number"; typeof "hello" gives "string"; typeof true gives "boolean". Since the result is a string, writing console.log(typeof 42) shows the word number on screen.

The typeof null pitfall

typeof null does not return "null" as you might expect; it returns "object". This is a historical bug from the early years of JavaScript; it could not be fixed later because old code would break.

So to check whether a value is null, do not use typeof. Use the direct comparison deger === null instead. This behavior is known as a pitfall; it surprises programmers who do not know it.

Exercise Print the type of three values with typeof

Find the type of a number, a string and null using typeof, and print each one with console.log.

Show example solution
console.log(typeof 42);
console.log(typeof "hello");
console.log(typeof null);

Test yourself

  1. What is the result of typeof 42?

    typeof 42
    • "number"
    • "string"
    • "integer"
    • "42"
    Show answer

    "number" — Correct. 42 is a number, so typeof returns "number".

  2. Find the type of 42 with typeof

    let sonuc = ____;
    Show answer
    let sonuc = typeof 42;
  3. Match each value to its typeof result

    42
    "number"
    "hello"
    "string"
    true
    "boolean"
    null
    "object"
  4. What is the result of typeof null?

    typeof null
    • "null"
    • "undefined"
    • "object"
    • "boolean"
    Show answer

    "object" — Correct. typeof null returns "object"; this is a historical bug.

All lessons in Beginner