Typeof array is an object in javascript

pestrinmarco

Marco Pestrin

Posted on December 8, 2020

Typeof array is an object in javascript

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)
Enter fullscreen mode Exit fullscreen mode

The result is

object
object
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

The result is

true
false
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

and the result will be the same as the previous one.

💖 💪 🙅 🚩
pestrinmarco
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.

Related