The typeof
operator in JavaScript is used to determine the type of a variable or expression. It returns a string indicating the data type of the operand. It is a unary operator that can be used with any operand in JavaScript.
Here are some examples of how to use the typeof
operator in JavaScript:
1. Using typeof
with a number:
let num = 42;
console.log(typeof num); // Output: "number"
In the above example, the typeof
operator is used to determine the data type of the variable num
, which is a number. The console.log statement will output "number"
.
2. Using typeof
with a string:
let str = "Hello, world!";
console.log(typeof str); // Output: "string"
In the above example, the typeof
operator is used to determine the data type of the variable str
, which is a string. The console.log
statement will output "string"
.
3. Using typeof
with a boolean:
let bool = true;
console.log(typeof bool); // Output: "boolean"
In the above example, the typeof
operator is used to determine the data type of the variable bool
, which is a boolean. The console.log
statement will output "boolean"
.
4. Using typeof
with null:
let nullValue = null;
console.log(typeof nullValue); // Output: "object"
In the above example, the typeof
operator is used to determine the data type of the variable nullValue, which is null
. However, typeof
will incorrectly return "object"
for null. This is a known bug in JavaScript and has been around since the language’s inception.
5. Using typeof
with undefined:
let undefinedValue;
console.log(typeof undefinedValue); // Output: "undefined"
In the above example, the typeof
operator is used to determine the data type of the variable undefinedValue
, which is undefined. The console.log
statement will output "undefined"
.
6. Using typeof
with an object:
let obj = { name: "John", age: 30 };
console.log(typeof obj); // Output: "object"
In the above example, the typeof
operator is used to determine the data type of the variable obj
, which is an object. The console.log
statement will output "object"
.
7. Using typeof
with a function:
function add(a, b) {
return a + b;
}
console.log(typeof add); // Output: "function"
In the above example, the typeof
operator is used to determine the data type of the function add
. The console.log
statement will output "function"
.
8. Using typeof
with an array:
let arr = [1, 2, 3];
console.log(typeof arr); // Output: "object"
In the above example, the typeof
operator is used to determine the data type of the variable arr
, which is an array. However, typeof
will return "object"
for arrays.
In conclusion, the typeof
operator is a useful tool for determining the data type of a variable or expression in JavaScript.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.