How does javascript logical assignment work?

前端 未结 6 978
無奈伤痛
無奈伤痛 2020-12-01 08:06

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

6条回答
  •  忘掉有多难
    2020-12-01 09:05

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

提交回复
热议问题