Borislav Hadzhiev
Sat Nov 27 2021·2 min read
Photo by Lê Tân
To check if a value is an object:
typeof variable === 'object'
.variable !== null
.!Array.isArray(variable)
.const variable = {name: 'Tom'}; if ( typeof variable === 'object' && variable !== null && !Array.isArray(variable) ) { console.log('✅ Value is an object'); } else { console.log('⛔️ Value is not an object'); }
We used the
logical AND (&&)
operator to chain 3 conditions in our if
statement.
All conditions have to pass for our if
block to run.
The first condition uses the
typeof
operator to check if a value has a type of "object"
.
The typeof
operator returns a string that indicates the type of a value. Here
are some examples.
console.log(typeof {}); // 👉️ "object" console.log(typeof []); // 👉️ "object" console.log(typeof null); // 👉️ "object" console.log(typeof function () {}); // 👉️ "function" console.log(typeof (() => {})); // 👉️ "function" console.log(typeof ''); // 👉️ "string" console.log(typeof 0); // 👉️ "number"
null
value also have a type of "object"
. To make sure the value does not store an array or null, we have to add 2 additional checks.Our second condition checks that the value is not equal to null
.
And the third - that the value is not an array.
If all of the conditions pass, we can conclude that the value is an object.
All of the following 3 types have a value of object:
{}
[]
null
valueAn alternative approach is to use the prototype property on the Object class.
// 👇️ true console.log(Object.prototype.toString.call({}) === '[object Object]'); // 👇️ false console.log(Object.prototype.toString.call([]) === '[object Object]'); // 👇️ false console.log(Object.prototype.toString.call(null) === '[object Object]');
We called to toString()
method on the prototype, passing it an object, an
array and null
.
The names of all 3 are different when stringified:
// 👇️️ "[object Object]" console.log(Object.prototype.toString.call({})); // 👇️ "[object Array]" console.log(Object.prototype.toString.call([])); // ️👇️ "[object Null]" console.log(Object.prototype.toString.call(null));
I try to avoid "magic" strings like [object Object]
as much as possible,
because they are prone to errors and difficult to debug.