Efim Rozovsky
Efim Rozovsky

Reputation: 383

why "true || undefined ? undefined : false;" returns "undefinied"?

I wrote this expression in chrome console:

true || undefined ? undefined : false;

and it returned:

undefined

How come? enter image description here

Upvotes: 2

Views: 484

Answers (5)

JacobIRR
JacobIRR

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

Majed Badawi
Majed Badawi

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

Ntjs95
Ntjs95

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

eamanola
eamanola

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

ShadowRanger
ShadowRanger

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

Related Questions