Last updated on September 18, 2023
In JavaScript, we can use the “typeof” operator to determine the data type of a value. The typeof operator helps you figure out what kind of data we’re working with. When we use “typeof” with a value as its input, it gives us information about the data typeof that value.
Syntax:
typeof value_or_variable;
typeof:
The typeof keyword represents the operator.value_or_variable:
It is the value or variable whose data type needs to check.Look at the below examples in which we are going to check the data type of different values.
Example 1: Check String Data Type
let customerName = "Henry";
console.log(typeof customerName);
// output: string
In this example, we assigned a string value containing the customer’s name “Henry” to the variable “customerName”. To check the datatype of the customerName variable, we are using typeof operator along with the console.log() function that returns “string” in the output which means the data type of the customerName variable is a string.
Example 2: Check Number Data Type
let productQuantity = 35;
console.log(typeof productQuantity);
// output: number
In this example, we assigned a numeric value of 35 to the variable productQuantity. To check the data type of the productQuantity variable we used typeof operator along with the JavaScript built-in function console.log() which returns number in the output which means the data type of the productQuantity is a number.
Example 3: Check Data Type of a Numeric String
let orderNumber = "40";
console.log(typeof orderNumber);
// output: string
In this example, we assigned a numeric string “40” to the variable orderNumber. Since it has double quotes it is treated as a string. As a result, the “typeof” operator returns “string” as the data type, and “console.log()” displays “string” as the output.
Conclusion:
In this article, we explained the JavaScript “typeof” operator, explained how it works, and discussed when to use it. We also provided three examples to illustrate how it determines data types based on variable assignments.