Reputation: 91
I don't understand why one scenario evaluates false and the other true.
Scenario 1:
> '' == ''
true
Scenario 2:
> '' == ('' || undefined)
false
Is scenario 2 not asking if (empty string) is equal to: (empty string) OR undefined?
I'm sure I'm missing something fundamental here, which is really what I'm trying to figure out. I can easily code around this, but I'd like to learn why it's happening... for next time, ya know?
Upvotes: 6
Views: 7824
Reputation: 268344
'' == ( '' || undefined )
Is not the same as
( '' == '' ) || ( '' == undefined )
It's more along the lines of:
var foo = '' || undefined; // Results in undefined
And then comparing foo
to an empty string:
foo == ''; // undefined == '' will result in false
The logical ||
is a short-circuiting operator. If the argument to its left is truthy, the argument to the right is not even evaluated. In JavaScript, ''
is not considered to be truthy:
if ( '' ) console.log( 'Empty Strings are True?' );
As such undefined
is returned and compared against an empty string. When you perform this logic within a the parenthesis, the ''
and the undefined
don't know about the impending equality check that is waiting to happen - they just want to know which of them is going to survive this evaluation.
Upvotes: 12
Reputation: 3241
try '' == '' || '' == undefined
As in almost all programming languages, the expressions at both sides of an operator must evaluate to a valid operand. ||
is logical OR operator which is used to evaluate a pair of boolean operands.
Upvotes: 1
Reputation: 150253
Let's break it:
'' == ('' || undefined) // return "undefined"
'' == undefined // false
||
return the first true value or the last value.
You want this:
'' == undefined || '' == false
undefined
is ==
only to null
, and not to all other "falsy" values:
Upvotes: 2