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 likeif
. 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';