Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript returning 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);

...While this works as expected, returning true:

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

I am basically just trying to do a simple shorthand check to see if a value exists in a variable (ensuring it's not undefined, null, or empty string).

I know I can do each test individually (x == null, typeof x == 'undefined', x == '') - I'm just trying to understand why Javascript returns a string on what looks to be a boolean test.

like image 391
kman Avatar asked Mar 28 '12 03:03

kman


1 Answers

When a conditional operator in JavaScript is satisfied, it returns the last value evaluated.

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

An empty string is falsey, so when you use just x in a condition, it will be false. Because you are using &&, if the LHS is false, then there is no reason to bother checking the RHS. This is short circuit evaluation. Therefore, the last evaluated part, the empty string, is returned to alert().

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

A non empty string is truthy. So the LHS is true, and because it's an &&, the RHS is evaluated (it needs to be to know if the entire condition is true). The return value of y.length > 0 is true, so that is passed to your alert().

like image 67
alex Avatar answered Oct 24 '22 04:10

alex