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?
Why
isArray()
is written onArray
instead ofArray 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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With