Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
Mr.7 Avatar asked Oct 15 '25 14:10

Mr.7


1 Answers

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

like image 56
T.J. Crowder Avatar answered Oct 18 '25 16:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!