In JavaScript, the typeof
operator is used to determine the type of a variable or an expression. It returns a string indicating the data type of the operand.
typeof variableName;
typeof(expression);
Behavior:
-
Primitive Types:
-
For primitive types (except null), typeof returns a string indicating the type:
typeof 42; // "number" typeof "Hello"; // "string" typeof true; // "boolean" typeof undefined; // "undefined"
-
For primitive types (except null), typeof returns a string indicating the type:
-
Objects:
-
For objects, except
null, typeof
returns "object
":typeof {}; // "object" typeof []; // "object" typeof new Date(); // "object"
-
For objects, except
-
Function:
-
typeof
returns "function
" for functions:typeof function() {}; // "function"
-
-
null:
-
typeof
null returns "object
", which is a historical quirk in JavaScript:typeof null; // "object"
-
-
Undefined Variables:
-
For undefined variables, typeof returns "undefined":
let x; typeof x; // "undefined"
-
For undefined variables, typeof returns "undefined":
-
typeof
is a unary operator, and it does not require parentheses when used. -
It's important to note that
typeof
has some quirks, like returning"object"
fornull
. This behavior is a historical mistake in the language and has been kept for backward compatibility reasons. -
typeof
is useful for performing type checks or determining the type of a variable before performing certain operations.
function example(value) {
if (typeof value === 'number') {
return 'It is a number';
} else if (typeof value === 'string') {
return 'It is a string';
} else {
return 'It is of another type';
}
}
console.log(example(42)); // Outputs: 'It is a number'
console.log(example('Hello')); // Outputs: 'It is a string'
console.log(example(true)); // Outputs: 'It is of another type'
typeof
is a handy tool for performing basic type checks, but for more comprehensive type checking or handling different object types, other methods or libraries might be neede