Mr.7
Mr.7

Reputation: 2713

Why `isArray()` is written on `Array` instead of `Array prototype`?

Out of curiosity, I just want to know the reason.

All array methods like map, forEach, reduce are written on Array.prototype and so that, i can use like this

let sum = [1,2,3,4,5].reduce( (acc, value) => acc+value, 0);
console.log(sum);

Unlike all these methods, isArray() usage is like

let isArray = Array.isArray([1,2,3]); // I can't use [1,2,3].isArray(); :(
console.log(isArray);

Is there any reason behind this?

Upvotes: 4

Views: 1393

Answers (3)

Slai
Slai

Reputation: 22876

Any Object can have .isArray() property:

o = { isArray: () => true }
console.log(o.isArray())      // true 

a = []; a.isArray = () => false
console.log(a.isArray())      // false

or .prototype.isArray():

Object.prototype.isArray = () => true
Array.prototype.isArray = () => false
console.log({}.isArray(), [].isArray()) // true false

Update never mind ..

Array.isArray = () => false
console.log(Array.isArray([]))    // false

but you can still add it:

Object.prototype.isArray = false
Array.prototype.isArray = true

console.log([].isArray, {}.isArray, "".isArray, (0).isArray, (false).isArray) // but doesn't work for null and undefined 

Upvotes: 0

marvel308
marvel308

Reputation: 10458

If the object is not typeof array. In that case we would have to add the method isArray() to all data types.

For example string.isArray() would return false, object.isArray() would return false etc.

Also as ponury-kostek pointed it out in the comments. Try doing that with null or undefined. It is not possible

It is better to have it as a function which takes an input and validates it

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074545

Why isArray() is written on Array instead of Array prototype?

In case the answer is "no, it's not an array":

let obj = {};
let isArray = obj.isArray(); // TypeError: obj.isArray is not a function

The purpose of isArray is to provide a means of checking whether something that may or may not be an array is an array. If isArray were on the Array prototype, it wouldn't be accessible unless the answer was "yes, it's an array."


To be fair, it would have been possible to put isArray on Object.prototype and have it return false, then override it in Array.prototype to return true. That still would have failed for undefined and null, though:

let x = null;
let isArray = x.isArray(); //  TypeError: Cannot read property 'isArray' of null

...and would have unnecessarily polluted the members list of all other object types in the standard library. Making it a static that you call with the thing to be tested as an argument just made more sense — at the point where Array.isArray was added. (What may have made more sense still would have been for typeof to work fundamentally differently than it does, but that ship sailed in 1995, so...)

Upvotes: 8

Related Questions