PASSWORD RESET

Your destination for complete Tech news

How to check if a value is an object in JavaScript?

326 0
< 1 min read

To check if a value is an object in JavaScript, you can use the typeof operator and check if the value is equal to "object". However, this will return true for both objects and arrays, so you may need to use an additional check to differentiate between the two. Here is an example:

function isObject(value) {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

Here’s how you can use this function:

let obj = { name: 'John' };
let arr = [1, 2, 3];
let num = 123;

console.log(isObject(obj)); // true
console.log(isObject(arr)); // false
console.log(isObject(num)); // false

Alternatively, you can use the Object.prototype.toString.call() method to check if a value is an object. This method will return the object type, so you can check if it is equal to "[object Object]". Here’s an example:

function isObject(value) {
  return Object.prototype.toString.call(value) === '[object Object]';
}

This method has the advantage of being able to distinguish between different types of objects (e.g., arrays, functions, etc.), but it is slightly more verbose and may be less efficient than the typeof operator.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.