JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

What is the typeof operator in JavaScript?

JavaScript is a loosely typed language which means you don't specify the data type of a variable while declaring it.

let x;

A variable in JavaScript can take any value. Suppose you have assigned a number to a variable and then later on in the code, you have assigned a string to that same variable. In that case, JavaScript won't give any errors.

let pi = 3.14;
pi = "Pie";
console.log(pi); //"Pie"

It is important for you to know the type of value stored in a variable. For this, JavaScript provides the typeof operator. The typeof operator is a unary operator mainly used to check the data type of a variable or value.

The following table shows the value returned by the typeof operator for any JavaScript value:

Value typeof value
Number such as 3.14, 10, etc. "number"
Boolean such as true or false "boolean"
String such as "Pizza", "Burger", etc. "string"
Function such as function sum(a,b){return a+b} "function"
Array such as [11,22,33,44] "object"
Object such as {name: 'Mohit Natani'} "object"
Any instance of a class "object"
null "object"
undefined "undefined"
BigInt "bigint"
Symbol "symbol"

In JavaScript, object, array, map, set, and instances of a class are called reference variables. So, when you use the typeof operator with a reference variable, the typeof operator returns "object". To check which class a reference variable belongs to, use the instanceof operator.

typeof operator Examples

Let's see some examples that show you how to use the typeof operator in JavaScript.

const PI = 3.14;
let food = "Pizza",
    arr = [11,22,33,44],
    boolean = false,
    pdt = {
      name: 'Blue Flared Jeans',
      price: 1199
    };

function sum(a, b){
  return a + b;
}

console.log(typeof PI); //"number"
console.log(typeof food); //"string"
console.log(typeof arr); //"object"
console.log(typeof boolean); //"boolean"
console.log(typeof pdt); //"object"
console.log(typeof sum); //"function"

You mainly use the typeof operator in an if statement to check whether a variable is of a particular type or not. For example, you can check whether a variable is a string or not by running the following code:

let food = "Pizza";
if(typeof food === "string"){
	console.log("Variable food is a string.");
}else{
	console.log("Variable food is not a string.");
}

Output

"Variable food is a string."

Recommended Posts