DEV Community

Marco Pestrin
Marco Pestrin

Posted on • Updated on

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.

Top comments (2)

Collapse
 
lexlohr profile image
Alex Lohr

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].

Collapse
 
sergeypodgornyy profile image
Sergey Podgornyy

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? 😉