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.
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;
As a function:
typeof (x);
It can work either with parentheses or without, the result will be the same.