Exploring typeof operator and perform type checking in JavaScript

According to the application requirement, we might need to do some type checking of the data that we are going to deal with. It is always better do a prior check on the data types before using it. For example:

const number1 = 45;

const number2 = "45";

Here both number1 and number2 values are same but there types are different. One is integer value and other is of type string. So if we will compare their values it will return true as values are same.

console.log(number1 == number2); // true

To compare both value and type, use “===” instead of “==”.

console.log(number1 === number2); // false

The typeof operator

The typeof operator used to check the type of a given value.

typeof true; // boolean

typeof 45; //number

typeof "45"; //string

typeof 2.6; //number

typeof [1, 2]; //object

typeof {x:5}; //object

Let’s check type of some falsy values.

typeof NaN; // number

typeof null; // object

typeof undefined; //undefined

typeof false; // Boolean

Some more examples:

function func() {
   //logic
}

typeof func; // function

class xyz {
//class body
}

typeof xyz; //function

Now as you know the use of typeof operator, you can use it to do your type checking.

Type checking for undefined values

if (typeof data !== 'undefined') {
     // your logic
}

Type checking for number values

function func(data) {
   if (typeof data === 'number') {
     data = data + 5;
   }  
   return data;
}

The same way you can perform type checking on data based on your requirement.

Leave a Reply

Your email address will not be published. Required fields are marked *