typeof
- Node.js course
- Beginner
- Lesson 17/116
- 5 min
Learn type checking with the typeof operator.
The typeof operator
The typeof operator returns a value's type as a string. It is your first tool to understand which type you are working with.
Examples: typeof 42 returns 'number', typeof 'hello' returns 'string', typeof true returns 'boolean', typeof undefined returns 'undefined'.
When you want to behave differently based on a variable's type, you write a condition like if (typeof x === 'number').
typeof quirks
typeof is mostly useful but has a few quirks. Knowing them saves you from surprises.
First: typeof null returns 'object'; this is an old design decision. Second: typeof function f() {} returns 'function'; this is expected behavior.
Third: typeof can be applied even to an undeclared variable without throwing an error; it returns 'undefined'. This is useful in some cases.
Practice Print types with typeof
Declare let n = 42, let s = 'hello', let b = true. Print all three types with console.log(typeof n), console.log(typeof s), console.log(typeof b).
Starter code
// Declare n, s, b variables
// Print their types with typeofSample solution
let n = 42;
let s = "hello";
let b = true;
console.log(typeof n);
console.log(typeof s);
console.log(typeof b);Expected output
number string boolean
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Check with typeof
if (____) { console.log('number'); }
if (typeof x === 'number') { console.log('number'); }
Explanation: You compare typeof's result with the string 'number'.
2 What does typeof null return?
- 'null'
- 'object' Correct answer
- 'undefined'
- 'boolean'
Explanation: typeof null interestingly returns 'object'.
3 Match the typeof results
| Term | Meaning |
|---|---|
typeof 42 |
'number' |
typeof 'a' |
'string' |
typeof true |
'boolean' |
typeof null |
'object' |