The most important reason that makes the MDN polyfill a safe one to use is that an array is an exotic object. The best way to differentiate an exotic object would be through the use of an exotic feature related to that object – that is to say, an exotic property of the exotic object.
If you look at the specification of the Object.prototype.toString method, you will find that it uses the abstract operation isArray, which checks for exotic array objects.
On the other hand look at the specification of the constructor property. It is not an exotic property of the array, and so javascript code can change it easily.
const x = [];
x.constructor = Object
In fact, the constructor property is more intended for meta programming. You could – in es5 – create subclasses without touching the constructor property.
Now, here are things that can go wrong with your implementation:
const customIsArray = function(arg) {
return arg.constructor === Array;
};
// 1) won't work with subclasses of Array
class CustomArray extends Array {
// ...
}
const customArray = new CustomArray()
customIsArray(customArray) // false
Array.isArray(customArray) // true
// 2) won't work across different realms (iframes, web workers, service workers ... if we are speaking about the browser environment)
const iframe = document.createElement('iframe')
document.body.appendChild(iframe)
const IframeArray = iframe.contentWindow.Array;
const iframeArray = new IframeArray();
customIsArray(iframeArray) // false
Array.isArray(iframeArray) // true
// 3) won't work with few edge cases like (customIsArray will return true, while Array.isArray will return false)
const fakeArray1 = { __proto__: Array.prototype }
const fakeArray2 = { constructor: Array }
customIsArray(fakeArray1) // true
Array.isArray(fakeArray1) // false
customIsArray(fakeArray2) // true
Array.isArray(fakeArray2) // false