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.
Summary. Because JavaScript is a loosely typed language, the operands of && and || can be of any type.
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).
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.
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.
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
.
&&
is sometimes called a guard operator.
variable = indicator && value
it can be used to set the value only if the indicator is truthy.
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