The `typeof` operator in JavaScript is used to determine the type of a variable or expression. It returns a string that represents the data type.
typeof operand
or
typeof (operand)
Here are some examples of the `typeof` operator in action:
Example 1: Checking a variable
let age = 25;
console.log(typeof age); // Output: "number"
In this example, the `typeof` operator is used to check the data type of the `age` variable, which is a number. The output will be the string "number".
Example 2: Checking a string
let name = "John";
console.log(typeof name); // Output: "string"
Here, the `typeof` operator is used to check the data type of the `name` variable, which is a string. The output will be the string "string".
Example 3: Checking an array
let numbers = [1, 2, 3, 4, 5];
console.log(typeof numbers); // Output: "object"
In this example, the `typeof` operator is used to check the data type of the `numbers` variable, which is an array. Arrays in JavaScript are considered as objects, so the output will be the string "object".
Example 4: Checking a boolean
let isActive = true;
console.log(typeof isActive); // Output: "boolean"
Here, the `typeof` operator is used to check the data type of the `isActive` variable, which is a boolean. The output will be the string "boolean".
Example 5: Checking an undefined value
let city;
console.log(typeof city); // Output: "undefined"
In this example, the `typeof` operator is used to check the data type of the `city` variable, which is currently undefined. The output will be the string "undefined".
Example 6: Checking a function
function sayHello() {
console.log("Hello!");
}
console.log(typeof sayHello); // Output: "function"
Here, the `typeof` operator is used to check the data type of the `sayHello` function. Functions are considered as objects in JavaScript, so the output will be the string "function".
Example 7: Checking null
let address = null;
console.log(typeof address); // Output: "object"
In this example, the `typeof` operator is used to check the data type of the `address` variable, which has a value of `null`. Surprisingly, `typeof null` returns "object" instead of "null". This is a historical bug in JavaScript.
These are just a few examples of the `typeof` operator. It can be used to check the types of various other JavaScript constructs as well, such as objects, dates, and symbols.