In javascript, if we have some code such as
var a = "one";
var b = q || a;
alert (b);
The logical OR operator will assign a's value to b, and the alert will be "one."
Is this limited to assignments only or can we use it everywhere?
It seems an empty string is treated the same as undefined. Is this right?
How does this work with AND variables? What about combinations of them?
What is a good example of when to use these idioms, or when not to?
Assignment (=)The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.
Description. Logical AND ( && ) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.
The ||= 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.
Logic operators are used to find the logic between variables in JavaScript. There are three logical operators in JavaScript: || (OR), && (AND), ! (NOT).
For your q || a
to evaluate to a
, q
should be a 'falsy' value. What you did is called "Short circuit evaluation".
Answering your questions:
The logical operators (like and - &&
, or - ||
) can be used in other situations too. More generally in conditional statements like if
. More here
Empty string is not treated as undefined
. Both are falsy values. There are a few more falsy values. More here
AND
, or &&
in JavaScript, is not a variable. It is an operator
The idiom you have used is quite common.
var x = val || 'default'; //is generally a replacement for
var x = val ? val : 'default' //or
if (val)
var x = val;
else
var x = 'default';
The way ||
works in Javascript is:
true
, return the left operand&& works similarly.
You can make use of this for in-line existence checks, for example:
var foo = (obj && obj.property)
will set foo
to obj.property
if obj
is defined and "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