What typeof does in JavaScript
The typeof operator in JavaScript returns a string that names the type of a value. Put it in front of the value or variable you want to check:
const count = 42;
const label = "items";
console.log(typeof count); // "number"
console.log(typeof label); // "string"
Parentheses are optional, so typeof(count) gives the same result.
The strings typeof returns
typeof returns one of these strings:
"undefined"for a variable that has no value"boolean"fortrueandfalse"number"for numbers, includingNaNandInfinity"bigint"for BigInt values, such as10n"string"for text"symbol"for symbols"function"for functions"object"for objects, arrays andnull
Checking a type
Compare the result with === to check for a type. The result is always a lowercase string, so the comparison has to match it exactly:
function greet(name) {
if (typeof name !== "string") {
return "Hello, friend";
}
return "Hello, " + name;
}
console.log(greet("Ana")); // Hello, Ana
console.log(greet(42)); // Hello, friend
Quirks to know
A few results surprise people:
typeof nullreturns"object". This is a long-standing quirk of the language. To check fornull, compare with=== nullinstead.- Arrays also return
"object". To check for an array, useArray.isArray(value). typeofon a name that was never declared returns"undefined"and does not throw an error. Using the name directly would throw aReferenceError.typeof NaNreturns"number", even though NaN stands for “not a number”.
Primitive types
What are the 7 primitive data types in JavaScript? They are string, number, bigint, boolean, undefined, symbol and null. Six of them have their own result from typeof. The exception is null, which returns "object", so it needs the separate check shown above.
How it compares with C++
Is C++ static or dynamic? C++ is statically typed. Each variable and expression has a type that the compiler works out before the program runs. JavaScript is dynamically typed. A variable can hold a number at one moment and a string the next, so typeof checks the value while the program is running.
For the C and C++ side of this, look at typeof in c and decltype. They ask the compiler for a type at compile time, instead of returning a string that you test at runtime.
In JavaScript, use typeof to check a value’s type as your code runs, and keep the null and array quirks in mind.