check javascript object not array and not null

How to check if a JavaScript object is not an array and not null

If you are working with JavaScript, there may be times when you need to check whether a variable is an object or not. In some cases, you may also need to check whether the object is an array or null. In this blog post, I will explain how to check if a JavaScript object is not an array and not null.

Using typeof Operator

The easiest way to check whether a variable is an object is to use the typeof operator. The typeof operator returns a string indicating the type of the operand. If the operand is an object, the typeof operator returns "object". If the operand is null, the typeof operator returns "object" as well. Therefore, we need to combine typeof with the null-checking operator as shown below:


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

The above code defines a function called isObject that takes a value as an argument and returns true if the value is an object and not an array or null.

Using instanceof Operator

Another way to check whether a variable is an object is to use the instanceof operator. The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor. In other words, it tests whether an object was created by a particular constructor. To check whether a variable is not an array and not null, we can use instanceof as shown below:


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

In the above code, instanceof is used to check whether the value is an instance of Object. The Array.isArray function is used to check whether the value is not an array, and the null-checking operator is used to check whether the value is not null.

Conclusion

Now you know how to check whether a JavaScript object is not an array and not null. You can use either typeof or instanceof operator to check whether a variable is an object or not. Both methods have their own advantages and disadvantages. The typeof operator is easy to use and works with null values, but it may return unexpected results for some values. The instanceof operator is more precise, but it doesn't work with null values, and it requires that you know the constructor of the object you want to test for.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe