Why Does Typeof Array with Objects Return "Object" and Not "Array"

Why does typeof array with objects return object and not array?

One of the weird behaviour and spec in Javascript is the typeof Array is Object.

You can check if the variable is an array in couple of ways:

var isArr = data instanceof Array;
var isArr = Array.isArray(data);

But the most reliable way is:

isArr = Object.prototype.toString.call(data) == '[object Array]';

Since you tagged your question with jQuery, you can use jQuery isArray function:

var isArr = $.isArray(data);

typeof object but not array

It is not quicker, but more precise, with a check for falsy values, like null, which is an object.

function isPlainObject(input) {
return input && !Array.isArray(input) && typeof input === 'object';
}

Why does typeof Array returns function and typeof [array variable] returns an Object?

When you write typeof Array, it means that you are getting type of constructor function. As class is under the hood is constructor function. Let me show an example:

class Person {
constructor(firstName, lastName, address) {
this.firstName= firstName;
this.lastName = lastName;
this.address= address;
}

getFullName () {
return this.firstName + " " + this.lastName ;
}
}

and to create an instance of the class:

let car = new Person ("Jon", "Freeman", "New York");

In the above code, we've created a variable car which references to function construtor defined in the class:

function Person (firstName, lastName, address) {
this.firstName = firstName,
this.lastName = lastName,
this.address = address,
this.getFullName = function () {
return this.firstName+ " " + this.lastName;
}
}

So this is a reason why typeof Array returns function.

Why does console.log() show an array, but typeof returns 'object'?

Solved: this was an issue with my Mongoose schema, specifically defining what should have been an array as an object with nested objects. Javascript's technicalities over arrays really being sugarcoated objects muddied the issue, causing console.log and typeof to present seemingly conflicting information; thank you to commenters for that piece of the puzzle!

JS typeOf(array) = 'object'

In JS everything but primitives are objects. Primitives are
: Numbers
, Booleans
, Null
, Undefined
, String
, Symbol

The rest are objects (arrays, objects, maps, sets...)

So typeof [] === "Object" typeof 123 === "number"

Javascript typeof() operator is returning a different value to the known variable type

That's because array is of type object

If you want to test a variable of array, you can use:

if (data.constructor === Array)
console.log('it's an array');

You can also use isArray() to check if it's an array like this:

if(typeof data === 'object' &&  
Array.isArray(data)) {
//Its an array
}


Related Topics



Leave a reply



Submit