js check data type

How to Check Data Type in JavaScript?

JavaScript is a dynamically typed language, which means that data types are determined automatically. However, sometimes it is necessary to check the data type of a variable before performing certain operations. In this blog post, we will explore different ways to check the data type in JavaScript.

Using typeof Operator

The typeof operator is a built-in function in JavaScript that returns the data type of an operand as a string.

let x = 42;
console.log(typeof x); // "number"

let y = "Hello, World!";
console.log(typeof y); // "string"

let z = true;
console.log(typeof z); // "boolean"

Using instanceof Operator

The instanceof operator is used to check if an object is an instance of a particular class or constructor function.

let myArray = [1, 2, 3];
console.log(myArray instanceof Array); // true

let myString = "Hello, World!";
console.log(myString instanceof String); // false

Using Object.prototype.toString() Method

The Object.prototype.toString() method returns a string representing the object.

let myNumber = new Number(42);
console.log(Object.prototype.toString.call(myNumber)); // "[object Number]"

let myFunction = function() {};
console.log(Object.prototype.toString.call(myFunction)); // "[object Function]"

In conclusion, there are several ways to check the data type in JavaScript, such as using the typeof operator, the instanceof operator, and the Object.prototype.toString() method. Each method has its own advantages and disadvantages, so it is important to choose the appropriate method based on the context.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe