Boot up your interpreter/console and try the comparison:
> ",,," == Array(4)
True
Why? At first I thought maybe since you could think of ",,," as an array of four characters with a ‘\0’ terminating slice, that might be why, but
> "..." == Array(4)
Returns "False". So… why? I know it’s some idiosyncratic bit of duck typing in JavaScript, but I am just curious what underlines this behavior. I gleaned this from Zed Shaw’s excellent presentation here, btw.
Because the right hand operand is converted to a string and the string representation of
Array(4)is,,,:If you use the array constructor function and pass a number, it sets the length of the array to that number. So you can say you have four empty indexes (same as
[,,,]) and the default string representation of arrays is a comma-separated list of its elements:How the comparison works is described in section 11.9.3 of the specification. There you will see (
x == y):(arrays are objects in JavaScript)
and if you follow the
ToPrimitivemethod you will eventually find that it it callstoString.