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.
When a conditional operator in JavaScript is satisfied, it returns the last value evaluated.
An empty string is falsey, so when you use just
xin 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 toalert().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 ofy.length > 0istrue, so that is passed to youralert().