FundamentalsChapter 17 of 21
typeof
Asking what a value is, and the three answers that mislead.
Asking the question
typeof returns a string naming the type of a value. It takes one operand and needs no brackets, though they do no harm.
JavaScript
console.log(typeof 'text');
console.log(typeof 3.14);
console.log(typeof false);
console.log(typeof {});Output
string number boolean object
The three answers that mislead
Three results are wrong, or at least unhelpful, and each has caught out a lot of people.
JavaScript
console.log(typeof null);
console.log(typeof []);
console.log(typeof NaN);Output
object object number
typeof nullis"object". This is a bug from 1995 that can never be fixed without breaking the web.typeof []is"object", because an array is one. UseArray.isArrayinstead.typeof NaNis"number", which is technically correct and rarely what you wanted to know.
Checking properly
JavaScript
const value = null;
console.log(value === null);
console.log(Array.isArray([1, 2]));
console.log(Number.isNaN(NaN));
console.log(Number.isInteger(4.0));Output
true true true true
It is safe on names that do not exist
typeof is the one operator that does not throw for an undeclared name, which is why it turns up in feature checks.
JavaScript
console.log(typeof neverDeclared);
if (typeof fetch === 'function') {
console.log('fetch is available');
}Output
undefined fetch is available
Note
That safety does not extend to let and const before their declaration. typeof on those still throws, because of the temporal dead zone.
Test yourself
2 questionsWhat does typeof null return?
Show the answer
"object" A bug from the first version of the language, kept because fixing it would break existing sites.
How should you check for an array?
Show the answer
Array.isArray(value) typeof reports "object" for arrays, and a length property proves nothing on its own.
Type Coercion
When JavaScript converts types for you, and how to take the wheel.