typeof OperatorThe typeof operator in JavaScript is a unary operator (meaning it operates on a single operand) that is placed before its operand. The operand can be a variable, a literal, or an expression of any type.
Its primary purpose is to evaluate the operand and return a string indicating its underlying data type. This makes typeof incredibly useful for type-checking and validation in your code.
typeof operand // or typeof(operand)
typeof Return ValuesThe typeof operator evaluates the operand and returns a lowercase string corresponding to its data type.
Here is a comprehensive list of the return values you can expect from the typeof operator:
| Data Type | String Returned by typeof |
|---|---|
| Number | "number" |
| String | "string" |
| Boolean | "boolean" |
| Object | "object" |
| Function | "function" |
| Undefined | "undefined" |
| Null | "object" |
Note on Null: You might notice that typeof null returns "object". This is a well-known historical bug in JavaScript that has been kept for backwards compatibility. null is a primitive value, not an object!
typeof OperatorThe following interactive example demonstrates how to implement the typeof operator to check whether variables are strings or numeric values using a conditional (ternary) operator.
let a = 10; let b = "String";// Check if 'b' is a string let resultB = (typeof b == "string" ? "B is String" : "B is Numeric"); console.log("Result => " + resultB);
// Check if 'a' is a string let resultA = (typeof a == "string" ? "A is String" : "A is Numeric"); console.log("Result => " + resultA);
What does the typeof operator return when evaluated against a function?