Lessons · JavaScript · typeof
What kind of value is this
typeof x returns a string naming the type: 'string', 'number', 'boolean', 'undefined', 'object', 'function'.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Data from a form, a URL or an API arrives as whatever it is, and a number that is secretly text breaks maths. typeof is the first check on anything you did not create yourself.
How to think about it
Compare typeof to the string you expect, in quotes. Know the two oddities: typeof null is 'object', and arrays are 'object' too, so use Array.isArray for those.
Worked example
console.log(typeof "hello");string.
console.log(typeof 42, typeof true);number boolean.
console.log(typeof undefined, typeof null);undefined object: null reporting object is a historic bug you have to know.
console.log(typeof [1, 2], Array.isArray([1, 2]));object true: arrays are objects; Array.isArray tells them apart.
Your turn
Only accept text.
if (typeof value === "")
Solve one with the tests running
The trap
typeof null is 'object'. Check for null with === null before trusting typeof, or a missing value passes as an object.
Practise typeof on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.