Skip to content
the poor coder

javascript check if object

Poor Man
Published
Reading time
2 min read
On this page

Javascript Check If Object#

As a web developer, I have come across a situation where I needed to check if a variable is an object or not in Javascript. There are many ways to do this, and I will explain some of them below.

Using typeof Operator#

The typeof operator returns a string indicating the type of the operand. We can use this operator to check if a variable is an object or not.

Text

let obj = {name: "Raju", age: 25};
if(typeof obj === "object") {
    console.log("obj is an object");
}

In the above code, we are checking if the obj variable is of type object using the typeof operator. If it is an object, we are logging a message to the console.

Using instanceof Operator#

The instanceof operator checks if an object is an instance of a specified object type. We can use this operator to check if a variable is an object or not.

Text

let obj = {name: "Raju", age: 25};
if(obj instanceof Object) {
    console.log("obj is an object");
}

In the above code, we are checking if the obj variable is an instance of the Object type using the instanceof operator. If it is an object, we are logging a message to the console.

Using toString() Method#

The toString() method returns a string representing the object. We can use this method to check if a variable is an object or not.

Text

let obj = {name: "Raju", age: 25};
if(Object.prototype.toString.call(obj) === "[object Object]") {
    console.log("obj is an object");
}

In the above code, we are calling the Object.prototype.toString() method on the obj variable to get its string representation. We are then checking if the string representation is equal to [object Object], which indicates that the variable is an object.

Conclusion#

These are some of the ways to check if a variable is an object or not in Javascript. It is important to use the correct method based on your use case and requirements.

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