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
?
Undefined typically refers to something which has not yet been assigned a value (yet). Null refers to something which definitively has no value. In that case, I would recommend returning a null. Note that a function with no specified return value implicitly returns undefined.
In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value. But if you then assign a = null; then a will now be null.
Both null and undefined are primitive values. Here is a full list: All other values in JavaScript are objects (objects, functions, arrays, etc.). Interestingly enough, when using typeof to test null, it returns object:
Undefined: It means the value does not exist in the compiler. It is the global object. You can see refer to “==” vs “===” article. It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist .
Because this[x]
is undefined
, which is falsy, and so is null
.
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...
false
undefined
null
""
NaN
0
Everything else is considered truthy.
So your expression will be evaluated as...
// v--falsey v--truthy! return it!
((((this[x] || null) || 'aïe') || 12) || undefined);
// ^--falsey ^--------^---these are not evaluated at all
Or you could look at it like this:
(
(
(
(this[x] || null) // return null
/* (null */ || 'aïe') // return 'aïe' and stop evaluating
|| 12)
|| undefined);
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