Javascript returns a string on what should be a shorthand boolean test

Can someone explain to me why this returns an empty string ("") instead of a boolean (false)?

var x = ""; alert(x && x.length > 0); 

... Although this works as expected, returns true:

 var y = "abc"; alert(y && y.length > 0); 

Basically, I'm just trying to do a simple verbatim check to see if a value exists in a variable (guaranteeing it is not undefined, null or an empty string).

I know that I can run each test individually (x == null, typeof x == 'undefined', x == ''). I'm just trying to understand why Javascript returns a string of what it looks like to be a boolean test.

+7
source share
3 answers

When a conditional statement is executed in JavaScript, it returns the last evaluated value.

 var x = ""; alert(x && x.length > 0); 

The empty string is false, so when you use only x in state, it will be false. Since you are using && , if the LHS is false, then there is no reason to worry about checking the RHS. This is a short circuit rating . Therefore, the last evaluated part, the empty string, is returned in alert() .

 var y = "abc"; alert(y && y.length > 0); 

A non-empty string is true. Thus, LHS is true, and since it is && , it is evaluated by RHS (it needs to know if the whole condition is true). The return value y.length > 0 is true , so it is passed to your alert() .

+7
source

It also returns an empty string, because x is already defined, just empty.

This causes the first part of your alert(x) expression to show an empty string.

If you need to check for a null / empty string, try something like this.

 String.isNullOrWhiteSpace = function (str) { if (typeof str === "string") { var isNullOrWhiteSpace = false; // Check for null string if (str == null || typeof str === "undefined") isNullOrWhiteSpace = true; // Check for string with whitespace if (str.replace(/\s/g, '').length < 1) isNullOrWhiteSpace = true; return isNullOrWhiteSpace; } if (typeof str === "undefined" || str == null) { return true; } }; 
0
source

Conditional operations using the && (AND) operator will stop when:

  • One of the conditions evaluated as false
  • He successfully completed it, evaluating everything to true

The result of conditional operations will be the last evaluated before stopping (not necessarily a boolean )

To force a real boolean , you can wrap everything around !!(...) , for example:

 alert(typeof !!(...) === "boolean"); //will always be true no matter what conditions are inside 
0
source

All Articles