How to Check if a Value is an Object in JavaScript

JavaScript provides the typeof operator to check the value data type. The operator returns a string of the value data type. For example, for an object, it will return "object". However, for arrays and null, "object" is returned, and for NaN/Infinity, "number" is returned.

It is somehow difficult to check if the value is exactly a real object. For example, null is not an object, but the result of typeof null is "object", which is an error in typeof. Null is a special value with a separate type of its own.

To check if a value is an object, the constructor of the value can be compared to Object.

// Returns if a value is an object
let obj = {
  siteName: 'W3Docs',
};
let str = 'W3Docs';
function isObject(objValue) {
  return objValue && typeof objValue === 'object' && objValue.constructor === Object;
}
let objVal = isObject(obj);
console.log(objVal);

let val = isObject(str);
console.log(val);
For objects that are created from classes, you can use the instanceof operator.

JavaScript Data Types

You do not have to define the type of the variable as it is effectively used by the JavaScript engine. Two types of data exist in JavaScript: primitive data type and non-primitive (reference) data type.

There are seven primitive data types in JavaScript:

  • Number
  • Bigint
  • String
  • Boolean
  • Null
  • Undefined
  • Symbol
  • and Object is a non-primitive data type.

All of these types are incapable of being changed except objects. Those that are unchangeable are called primitive values.

The typeof operator

The typeof operator helps us to see which type is stored in a variable. It supports two forms of syntax:

As an operator:

typeof x;

let value1 = 12345; 
console.log(typeof value1) // number
let value2 = 'string'; 
console.log(typeof value2) // string
let value3 = { key: 'value' };
console.log(typeof value3) // object
let value4 = true;
console.log(typeof value4); // object

As a function:

typeof (x);

It can work either with parentheses or without, the result will be the same.

function doSomething(value) {
  if(typeof(value) === 'string') {
    console.log('value is a string')
  } else if(typeof(value) === 'number') {
    console.log('value is a number');
  }else if(typeof(value) === 'object') {
    console.log('value is a object');
  }
}
doSomething("string");
doSomething(123);
doSomething({key: "value"});

Do you find this helpful?

Related articles