Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Empty String Comparison

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?

like image 327
Aaron Francis Avatar asked May 21 '12 19:05

Aaron Francis


People also ask

How do you compare empty strings?

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.

How do you check whether a string is empty or not in JavaScript?

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.

Is empty string null in JavaScript?

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.

How do I check if a string is empty?

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.


2 Answers

'' == ( '' || 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

Explanation

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.

like image 162
Sampson Avatar answered Nov 14 '22 23:11

Sampson


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:

  • 0
  • "" - empty string
  • NaN
  • false
like image 30
gdoron is supporting Monica Avatar answered Nov 14 '22 22:11

gdoron is supporting Monica