Why does javascript prefers to return a String over any other choices ?
Consider the following snippet.
var arr = ['Hello1', 'Hello2', 'Hello3'];
Array.prototype.item = function(x) {
return this[x] || null || 'aïe' || 12 || undefined ;
};
console.log( arr.item(43) ); // returns aïe
I intentionally called a non-existent array element.
However i cannot understand why does arr.item(43) returns the String ? Why not null or undefined or even 12 ?
Because
this[x]isundefined, which is falsy, and so isnull.The
||operator returns the first “truthy” value it finds, and stops its evaluation at that point.If no “truthy” value is found, it returns the result of the last operand evaluated.
There are a total of 6 “falsey” values. They are…
falseundefinednull""NaN0Everything else is considered truthy.
So your expression will be evaluated as…
Or you could look at it like this: