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.
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()
.
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