JavaScript – How Logical Assignment Works

javascriptlogical-operatorsvariable-assignment

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

Related Question