&& problem assessment

As far as I know, logical && works as follows

 var test = false; var foo = test && 42; 

This code assigns 42 foo only if the first condition evaluates to true . Therefore, in this example, foo will keep the current value.

I am wondering why this snippet doesn't work at all:

 var test = ""; var foo = test && 42; 

Now foo gets the value from test . I am very confused. An empty line is one of the values โ€‹โ€‹of the Javascript fake, so why the && operator could not execute this script?

Can someone help me with the spec on this, please?

+6
source share
2 answers

You yourself answered your question.

 var foo = test && 42; 

42 will be assigned to foo only if test evaluates to true .

So if test is an empty string (calculated as false), then 42 will not be assigned to foo , foo will be an empty string.

+4
source

You misunderstand the operator.
foo = x && y will always assign foo .

The && operator evaluates its leftmost "false" operand.

false && 42 evaluates to false; "" && 42 means "" .

var foo = test && 42; assigns false foo .

+7
source

Source: https://habr.com/ru/post/923971/


All Articles