Skip to content
Home » Program to Check if a Value is an Object in JavaScript

Program to Check if a Value is an Object in JavaScript

In this blog post, we will discuss a simple JavaScript program that checks whether a given value is an object or not. We will walk through the code snippet and provide an explanation of how it works.

Code

const test = {};
function isObject(val) {
    return val instanceof Object; 
}
console.log(isObject(test));

Code Explanation

The provided code snippet contains a JavaScript function named isObject that takes in a value as a parameter. Inside the function, it utilizes the instanceof operator to determine if the value is an instance of the Object class.

Here’s how the code works:


const test = {}; // Declare a variable named 'test' and assign an empty object to it

function isObject(val) { // Declare a function named ‘isObject’ that takes a parameter ‘val’

return val instanceof Object; // Use the ‘instanceof’ operator to check if the ‘val’ is an instance of ‘Object’ class

}

console.log(isObject(test)); // Call the 'isObject' function with 'test' as an argument and log the result to the console

In the code, we first declare a variable called test and assign an empty object to it. Then, we define a function isObject that takes in a parameter val. Inside the function, we use the instanceof operator to check if the value passed to the function (val) is an instance of the Object class. The instanceof operator returns true if the value is an object, and false otherwise.

Finally, we call the isObject function with the test variable as an argument and log the returned result to the console. If the test variable is indeed an object, the output will be true. Otherwise, it will be false.

This program can be useful when you need to determine whether a given value is an object or not in your JavaScript code. It can be handy for performing conditional checks or for type validation.

Conclusion

In this blog post, we have discussed a simple JavaScript program that checks if a given value is an object or not. The code snippet uses the `instanceof` operator to perform the check and returns `true` if the value is an object and `false` otherwise. We hope this program will be helpful to the students and working professionals in their JavaScript programming endeavors.

Also checkout the following codes.


How to Format and Group Refunds in JavaScript
How to Create a Yup Schema for Validation in JavaScript