How does javascript logical assignment work?
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 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';
The way ||
works in Javascript is:
- If the left operand evaluates as
true
, return the left operand - Otherwise, return the right 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".
I'm not quite sure I follow your question. You can use an expression anywhere you can use an expression, and a logical operator on two expressions results in an expression.
alert(q||a);alert(true||false);var x=5;var y=0;if (y!=0 && x/y>2) { /*do something*/ }
The last bit is useful. Like most languages, Javascript 'short-circuits' ANDs and ORs. If the first part of an AND is false, it doesn't evaluate the second bit - saving you a divide-by-0. If the first part of an OR is true, it doesn't evaluate the second.
But you can use boolean operators anywhere you can use an expression.