This is from Crockford’s JavaScript: The Good Parts
var is_array = function (value) {
return Object.prototype.toString.apply(value) === '[object Array]';
};
Would this code have worked just as well if he had used a simple equality compare == instead of the identity compare ===?
My understanding of identity is that it allows you to check if a value is really set to something specific, and not just something equivalent. For example:
x == true
Will evaluate to true if x is 1, or true, but
x === true will only be true if x is true.
Is it ever possible for the is_array function above to work with either == or ===, but not the other?
In this particular case
==and===will work identically.There would be no real difference in this case because both sides of the quality test are already strings so the extra type conversion that
==could do won’t come into play here. Since there’s never any type conversion here, then==and===will generate the same result.In my own personal opinion, I tend to use
===unless I explicitly want to allow type conversion as I think there is less likelihood of getting surprised by some result.