Often there is a need to compare variable types in javascript
const arr = [2,4,6,8]
const obj = { type: ‘serviceBot’, valid: true }
console.log(typeof arr)
console.log(typeof obj)
The result is
object
object
Apparently there seems to be something wrong because the array is recognized as an object and seems to be no real difference between object and array.
This because in javascript all derived data type is always a type object. Included functions and array.
In case you need to check if it’s an array you can use isArray method of Array.
const arr = [2,4,6,8]
const obj = { type: ‘serviceBot’, valid: true }
console.log(Array.isArray(arr))
console.log(Array.isArray(obj))
The result is
true
false
otherwise there is a instanceOf operator
const arr = [2,4,6,8]
const obj = { type: ‘serviceBot’, valid: true }
console.log(arr instanceOf Array)
console.log(obj instanceOf Array)
and the result will be the same as the previous one.
Top comments (2)
Class instances are also objects. An array literal is just an instance of the Array global constructor. Side note: overwriting the globalThis.Array/Object class can be (ab)used to steal data for example from JSONp responses.
If you want to know the actual type of the object, have a look at
Object.prototype.toString.call(arr)
, which should result in[object Array]
.That's because JavaScript is a prototype-based language 🙂 And more interesting is to check is the variable an object.
Do you know how? or should I share my solution? 😉