In JavaScript, both objects and arrays (among others) are ... objects. This subject has been debated a lot, and mainly because it is often important to distinguish exactly between array and objects (I am referring to Type Object and Array ). p>
This is actually a part of the language that is "incomplete". To complete this flaw, in version 5 of EcmaScript, a new method was implemented to help this destination: Array.isArray(var)
This new method, available in modern browsers (IE9 +) allows to clear the doubts. That is:
Array.isArray({}) // false
Array.isArray([]) // true
Before this was possible, there were different, more laborious ways to come to the same conclusion. One of them is suggested in MDN as Polyfil. Adding this code it detects if the browser supports .isArray()
and adds the method to Array if necessary:
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
In the background an object is Array if the following is true:
Object.prototype.toString.call(arg) === '[object Array]'
The morality of a function / method returning an object is because Arrays and Objects in JavaScript are instances of Object . This is more or less like grammar, you have to learn and accept that it is like this:)
Example (and another way to distinguish Arrays from Objects):
var a = [];
var o = {};
a instanceof Array // true
o instanceof Array // false <---
a instanceof Object // true
o instanceof Object // true