Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript AND operator within assignment

I know that in JavaScript you can do:

var oneOrTheOther = someOtherVar || "these are not the droids you are looking for..."; 

where the variable oneOrTheOther will take on the value of the first expression if it is not null, undefined, or false. In which case it gets assigned to the value of the second statement.

However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?

var oneOrTheOther = someOtherVar && "some string"; 

What would happen when someOtherVar is non-false?
What would happen when someOtherVar is false?

Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.

like image 790
Alex Avatar asked Jul 02 '10 05:07

Alex


People also ask

Can you use && in JavaScript?

Summary. Because JavaScript is a loosely typed language, the operands of && and || can be of any type.

What does && and || mean in JavaScript?

If applied to boolean values, the && operator only returns true when both of its operands are true (and false in all other cases), while the || operator only returns false when both of its operands are false (and true in all other cases).

What is logical and assignment operator?

The ||= is pronounced as “Logical OR assignment operator” and is used in between two values. If the first value is falsy, then the second value is assigned. It is evaluated left to right.

Is == an assignment operator?

The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not. If so, it returns true.


2 Answers

Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:

true && "foo"; // "foo" NaN && "anything"; // NaN 0 && "anything";   // 0 

Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty string, and of course false, anything else coerces to true.

like image 153
Christian C. Salvadó Avatar answered Sep 29 '22 10:09

Christian C. Salvadó


&& is sometimes called a guard operator.

variable = indicator && value 

it can be used to set the value only if the indicator is truthy.

like image 36
mykhal Avatar answered Sep 29 '22 09:09

mykhal