How does javascript logical assignment work?

前端 未结 6 973
無奈伤痛
無奈伤痛 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 08:59

    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".

提交回复
热议问题