Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

&& evaluation issue

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 ?

like image 264
Andre Meinhold Avatar asked Aug 28 '12 15:08

Andre Meinhold


2 Answers

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.

like image 174
SLaks Avatar answered Sep 21 '22 00:09

SLaks


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.

like image 41
xdazz Avatar answered Sep 19 '22 00:09

xdazz