Js Typeof in JavaScript
typeof Operator in JavaScript
The typeof operator is used to determine the type of a JavaScript variable or expression. It returns a string indicating the type.
Syntax
typeof operandoperandcan be a variable, literal, or expression.
Possible Return Values of typeof
| Type | Returned String | Example |
|---|---|---|
| Number | "number" | typeof 42 ? "number" |
| String | "string" | typeof "hello" ? "string" |
| Boolean | "boolean" | typeof true ? "boolean" |
| Undefined | "undefined" | typeof undefined ? "undefined" |
| Object | "object" | typeof {} ? "object" |
| Function | "function" | typeof function() {} ? "function" |
| Symbol | "symbol" | typeof Symbol() ? "symbol" |
| BigInt | "bigint" | typeof 123n ? "bigint" |
| Null* | "object" | typeof null ? "object" (quirk) |
Note:
typeof nullreturning"object"is a known JavaScript quirk.
Examples
console.log(typeof 123); // "number"console.log(typeof "JavaScript"); // "string"console.log(typeof true); // "boolean"console.log(typeof undefined); // "undefined"console.log(typeof {}); // "object"console.log(typeof null); // "object" (special case)console.log(typeof function(){}); // "function"console.log(typeof Symbol("id")); // "symbol"console.log(typeof 10n); // "bigint"Using typeof in Conditions
let value = 42;if (typeof value === "number") { console.log("It's a number!");} else { console.log("Not a number");}If you want, I can show you how to reliably check for null or arrays beyond just typeof!