How to Check If a Value is an Object in JavaScript

To check if a value is an Object in JavaScript, you can use the “typeof” operator, “instanceof” operator, or “Object.prototype.toString.call()” function.

Method 1: Using the typeof operator

The “typeof operator” returns a string representing the value type. To check if a value is an Object, you can compare the result of typeof with the string “Object”. However, this method considers null an Object, so you must add a check to exclude null values.

Example

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

const objectValue = { key: 'value' };
const nullValue = null;
const stringValue = 'hello';

console.log(isObject(objectValue));
console.log(isObject(nullValue));
console.log(isObject(stringValue));

Output

true
false
false

Method 2: Using the instanceof operator

The “instanceof operator” checks if a value is an instance of the specific class or constructor. For example, you can use instanceof with the Object constructor to check if a value is an object. However, like the typeof operator, this method considers null an Object, so you must add a check to exclude null values.

Example

function isObject(value) {
  return value !== null && value instanceof Object;
}

const objectValue = { key: 'value' };
const nullValue = null;
const stringValue = 'hello';

console.log(isObject(objectValue));
console.log(isObject(nullValue));
console.log(isObject(stringValue));

Output

true
false
false

Method 3: Using the Object.prototype.toString.call() function

The Object.prototype.toString.call() function returns a string representing the value type. Unlike the typeof operator and the instanceof operator, this method does not consider null an Object. You can use this method to check if a value is an object by comparing the result with the string ‘[object Object]’.

Example

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

const objectValue = { key: 'value' };
const nullValue = null;
const stringValue = 'hello';

console.log(isObject(objectValue));
console.log(isObject(nullValue));
console.log(isObject(stringValue));

Output

true
false
false

Each method has pros and cons, so choose the one that best suits your needs based on their behavior and compatibility with your specific use case.

Leave a Comment