What is a JavaScript typeof Operator?

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 1: Check String Data Type

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.


Written by
I am Siraj, a results-driven web developer with three years of hands-on experience in both frontend and backend development. My passion for creating seamless digital experiences drives me to continuously innovate and excel in my field.

Share on:

Related Posts

Improved by: Ayaz Ali Shah

Tags: JavaScript,