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?
Using equals Method This technique can be used to check the emptiness of String as well. All you need to do is to call equals() method on empty String literal and pass the object you are testing as shown below : String nullString = null; String empty = new String(); boolean test = "". equals(empty); // true System.
Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.
The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.
The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.
'' == ( '' || 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.
Let's break it:
'' == ('' || undefined) // return "undefined"
'' == undefined // false
||
return the first true value or the last value.
DEMO
You want this:
'' == undefined || '' == false
undefined
is ==
only to null
, and not to all other "falsy" values:
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