JavaScript : typeof
In JavaScript, the typeof operator is used to determine the type of a variable or expression. It returns a string indicating the data type of the operand. Here's how it works:
Syntax:
typeof operand
- operand : The variable or expression whose type needs to be determined.
Example:
let num = 10;
let str = 'Hello';
let bool = true;
let arr = [1, 2, 3];
let obj = { name: 'John', age: 30 };
let func = function() {};
console.log(typeof num); // Output: 'number'
console.log(typeof str); // Output: 'string'
console.log(typeof bool); // Output: 'boolean'
console.log(typeof arr); // Output: 'object' (Arrays are objects in JavaScript)
console.log(typeof obj); // Output: 'object'
console.log(typeof func); // Output: 'function'
Notes:
- typeof returns a string representing the data type of the operand.
- It can be used with variables, literals, or expressions.
- It's important to note that typeof null returns object , which is considered a historical bug in JavaScript. It does not mean that null is actually an object. Similarly, typeof returns object for arrays and functions, which are special kinds of objects.
- typeof` returns undefined if the operand has not been initialized or declared.
- When used with non-objects (primitive values), typeof returns number , string , boolean , undefined , or bigint (for BigInts).
- When used with objects, typeof returns object , except for functions, where it returns function.
- typeof is a unary operator, meaning it only takes one operand.
The typeof operator is useful for type checking and performing different operations based on the type of a variable or expression in JavaScript.