Why does javascript prefers to return a String
over any other choices ?
Consider the following snippet.
var arr = [\'Hello1\', \'Hello2\', \
The code a || b
is roughly equivalent to a ? a : b
, or this slightly more verbose code:
if (a) {
result = a;
} else {
result = b;
}
Since ||
is left-associative the expression a || b || c
is evaluated as (a || b) || c
.
So in simple terms this means that the ||
operator when chained returns the first operand that is "truthy", or else the last element.
This feature can be useful for providing defaults when you have missing values:
var result = f() || g() || defaultValue;
You could read this as: Get the result of f(). If it's a falsey value, then try g(). If that also gives a falsey value, then use defaultValue
.