CodeBlanks Logo Icon CodeBlanks

The typeof operator

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.

Practice 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.

Starter code

script.js
// print the type of a number
// print the type of a string
// print the type of null

Sample solution

script.js
console.log(typeof 42);
console.log(typeof "hello");
console.log(typeof null);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the result of typeof 42?

script.js
typeof 42
  • "integer"
  • "string"
  • "number" Correct answer
  • "42"

Explanation: 42 is a number, so typeof returns "number".

2 Find the type of 42 with typeof

Question
let sonuc = ____;
Answer
let sonuc = typeof 42;

Explanation: The typeof operator takes the value with a space.

3 Match each value to its typeof result

Term Meaning
42 "number"
"hello" "string"
true "boolean"
null "object"

4 What is the result of typeof null?

script.js
typeof null
  • "null"
  • "undefined"
  • "boolean"
  • "object" Correct answer

Explanation: typeof null returns "object"; this is a historical bug.

All lessons in Beginner