Typeof array is an object in javascript
Marco Pestrin
Posted on December 8, 2020
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.
💖 💪 🙅 🚩
Marco Pestrin
Posted on December 8, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.