JavaScript
This page explains how the typeof operator reports the type of a value at runtime.
Goal: use typeof to inspect values and understand its important exceptions for null, arrays, functions, and undeclared names.
The typeof operator
typeof returns a string describing the type of its operand. It is useful when a function accepts values of different kinds or when you are debugging a condition.
JavaScript
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object"
typeof {}; // "object"
typeof function () {}; // "function"Check a function argument
JavaScript
function greet(name) {
if (typeof name === "string") {
return "Hello, " + name + "!";
}
return "Please provide a name.";
}
greet("Alice"); // Hello, Alice!
greet(42); // Please provide a name.Important exceptions
typeof nullis"object"for historical reasons. Checkvalue === nullexplicitly when you need to distinguish null.typeof []is also"object". UseArray.isArray(value)to identify an array.- Functions return
"function", even though functions are objects in JavaScript. typeof notDeclaredreturns"undefined"without throwing, but reading an undeclared name directly does throw. A declared variable containingundefinedis a different case.