Reputation: 383
I wrote this expression in chrome console:
true || undefined ? undefined : false;
and it returned:
undefined
Upvotes: 2
Views: 484
Reputation: 8946
true or <literally any other value>
...is always true.
“Or” statements return the first true item they encounter, if one is present. “And” statements return the last true item if present.
Upvotes: 0
Reputation: 28404
The condition (true || undefined
) is true
, hence, the ternary operator will take undefined
as the result:
const condition = true || undefined;
console.log("condition:", condition);
console.log("result:", condition ? undefined : false);
If your goal is to split by the ||
:
const result = true || (undefined ? undefined : false);
console.log("result:", result);
Upvotes: 3
Reputation: 127
You want to use something like this:
function IsSomething(bool){
return bool || bool === undefined;
}
The problem with "true || undefined" is that the answer to this is undefined, which is why you are seeing undefined returned.
Upvotes: 0
Reputation: 434
the expression is equivalent to:
if (true) {
return undefined;
} else if (undefined) {
return undefined;
} else {
return false;
}
so it's return the first undefined
.
Upvotes: 1
Reputation: 155323
||
is higher precedence than ?:
, making the expression equivalent to (true || undefined) ? undefined : false;
. Thus, it evaluates true || undefined
first, which evaluates to true
, then chooses the truthy side of the :
, undefined
.
Upvotes: 2