How does javascript logical assignment work?

前端 未结 6 957
無奈伤痛
無奈伤痛 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:10

    This behavior is shared with other scripting languages like Perl. The logical OR operator can be used as a syntactic shorthand for specifying default values due to the fact that the logical OR operator stops evaluating its operands when it encounters the first expression that evaluates to true: "evaluate the first operand and if the value is interpreted as not false, assign it. Otherwise repeat for the second operand."

    I find I often use this behavior to specify default values for function parameters. E.g.

    function myFunction(foo, bar) {
        var fooValue = foo || "a";
    
        // no need to test fooValue -- it's guaranteed to be defined at this point
    }
    

提交回复
热议问题