How does javascript logical assignment work? How does javascript logical assignment work? javascript javascript

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:

  1. The logical operators (like and - &&, or - ||) can be used in other situations too. More generally in conditional statements like if. More here

  2. Empty string is not treated as undefined. Both are falsy values. There are a few more falsy values. More here

  3. AND, or && in JavaScript, is not a variable. It is an operator

  4. 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:

  1. If the left operand evaluates as true, return the left operand
  2. 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.