JavaScript typeof
In JavaScript, the typeof operator is used to determine the data type of a given operand.
It returns a string indicating the type of the operand.
Example
typeof
operand
The typeof Operator
The typeof operator returns one of the following string values:
- "undefined": If the operand is undefined.
- "boolean": If the operand is a boolean value (true or false).
- "number": If the operand is a number, including integers, floats, and NaN (Not-a-Number).
- "string": If the operand is a string.
- "bigint": If the operand is a BigInt.
- "symbol": If the operand is a symbol.
- "object": If the operand is an object (excluding null and arrays).
- "function": If the operand is a function.
Example
console.log(typeof undefined); // Output: "undefined" console.log(typeof true); // Output: "boolean" console.log(typeof 42); // Output: "number" console.log(typeof 'Hello'); // Output: "string" console.log(typeof {}); // Output: "object" console.log(typeof []); // Output: "object" (arrays are also objects) console.log(typeof null); // Output: "object" (Note: null is a known quirk, it should be null) console.log(typeof function() {}); // Output: "function"
The Data Type of typeof
The typeofoperator is not a variable. It is an operator. Operators ( + - * / ) do not have any data type.
But, the typeof operator always returns a string (containing the type of the operand).
The constructor Property
The constructor property returns the constructor function for all JavaScript variables.
Example
"John".constructor // Returns function String() {[native code]} (3.14).constructor // Returns function Number() {[native code]} false.constructor // Returns function Boolean() {[native code]} [1,2,3,4].constructor // Returns function Array() {[native code]} {name:'John',age:34}.constructor // Returns function Object() {[native code]} new Date().constructor // Returns function Date() {[native code]} function () {}.constructor // Returns function Function(){[native code]}
The instanceof Operator
The instanceof operator returns true if an object is an instance of the specified object:
Example
const cars = ["Saab", "Volvo", "BMW"]; (cars instanceof Array); (cars instanceof Object); (cars instanceof String); (cars instanceof Number);
The void Operator
In JavaScript, the void operator is used to evaluate an expression and return undefined.