How to check variable is an object in JavaScript?
In the JavaScript world, any value is either an object or a primitive value. We know that JavaScript has 7 primitive data types: string, number, bigint, boolean, undefined, symbol, and null. Primitive data is not an object and has no methods.
What is an object?
In JavaScript, an object is a standalone entity, with properties and type. Following are some of the examples of objects:
- {“a”: 1, “b”: 2} — objects created using literal notation
- Object.prototype
- everything descended from Object.prototype
- Function.prototype
- Object
- Function
- function getUser(){} — user-defined functions
- getUser.prototype — the prototype property of a user-defined function
- new getUser() — “new”-ing a user-defined function
- Math
- Array.prototype
- arrays
- new Number(3) — wrappers around primitives
- Object.create(null)
- everything descended from an Object.create(null)
- … others
a
is object
As we know the array, function, etc are objects. The following code will check a variable is an object including array, function, etc. It only excludes null.
typeof variable === 'object' && variable !== null
If we want to exclude arrays we need to add a check for arrays too. Following is the code that excludes arrays.
typeof variable === 'object' && variable !== null && !Array.isArray(variable)