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

Leave a Comment