Skip to content
the poor coder

js check data type

Poor Man
Published
Reading time
1 min read
On this page

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.

Text
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.

Text
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.

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC