As far as I know, The logical && works like the following
var test = false;
var foo = test && 42;
This code, will assign 42 to foo only if the first condition gets evaluated to true. So in this example, foo will keep its current value.
I'm wondering why this snippet doesn't work at all:
var test = "";
var foo = test && 42;
Now, foo gets the value from test assigned. I'm very confused. The empty string is one of Javascripts falsy values, so why would the && operator fail in this scenario ?
Can someone help me out with the spec on this one please ?
You're misunderstanding the operator.foo = x && y will always assign foo.
The && operator evaluates to its left-most "falsy" operand.
false && 42 evaluates to false; "" && 42 evaluates to "".
var foo = test && 42; assigns false to foo.
You have answered your question yourself.
var foo = test && 42;
42 will be assigned to foo only if test evaluated to true.
So if test is empty string (evaluated to false), 42 won't assigned to foo, foo will be the empty string.
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