How does javascript logical assignment work?

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

    I'm not quite sure I follow your question. You can use an expression anywhere you can use an expression, and a logical operator on two expressions results in an expression.

    alert(q||a);
    alert(true||false);
    
    var x=5;
    var y=0;
    if (y!=0 && x/y>2) { /*do something*/ }
    

    The last bit is useful. Like most languages, Javascript 'short-circuits' ANDs and ORs. If the first part of an AND is false, it doesn't evaluate the second bit - saving you a divide-by-0. If the first part of an OR is true, it doesn't evaluate the second.

    But you can use boolean operators anywhere you can use an expression.

提交回复
热议问题