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?
Best Answer
For your
q || a
to evaluate toa
,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 likeif
. More hereEmpty string is not treated as
undefined
. Both are falsy values. There are a few more falsy values. More hereAND
, or&&
in JavaScript, is not a variable. It is an operatorThe 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';