How do I check if a value is an object in JavaScript?
Richard W
richard w profile pic

In JavaScript, you can use thetypeof operator to check if a value is an object. However, it's important to note thattypeof has some quirks and may not always provide the desired result, especially when dealing with special object types like arrays or null values. To perform a more robust check, you can consider the following approaches: 1. Using thetypeof operator: - Usetypeof value === 'object' to check if the value is an object. This will include objects, arrays, and null values. - Keep in mind thattypeof null returns'object', which can lead to a false positive if you're specifically checking for non-null objects. 2. Using theinstanceof operator: - Usevalue instanceof Object to check if the value is an instance of theObject class. This approach doesn't considernull as an object. 3. Using theObject.prototype.toString() method: - UseObject.prototype.toString.call(value) === '[object Object]' to check if the value is an object. This method provides more accurate results, distinguishing between objects, arrays, and other special types. - This approach handles null values correctly by returning[object Null] for null values. Here's an example implementation that combines these approaches:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

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

// Usage example:
console.log(isObject({})); // Output: true
console.log(isObject([])); // Output: false
console.log(isObject(null)); // Output: false
console.log(isObject(42)); // Output: false

In the example above, theisObject() function checks if the value is of type'object', notnull, and has atoString() representation of[object Object]. This ensures that the value is a non-null object. By combining these techniques, you can perform a reliable check to determine if a value is an object in JavaScript.