Javascript AND operator within assignment

后端 未结 6 724
滥情空心
滥情空心 2020-11-22 05:20

I know that in JavaScript you can do:

var oneOrTheOther = someOtherVar || \"these are not the droids you are looking for...\";

where the va

6条回答
  •  太阳男子
    2020-11-22 05:45

    According to Annotated ECMAScript 5.1 section 11.11:

    In case of the Logical OR operator(||),

    expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

    In the given example,

    var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...move along";

    The result would be the value of someOtherVar, if Boolean(someOtherVar) is true.(Please refer. Truthiness of an expression). If it is false the result would be "these are not the droids you are looking for...move along";

    And In case of the Logical AND operator(&&),

    Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

    In the given example,

    case 1: when Boolean(someOtherVar) is false: it returns the value of someOtherVar.

    case 2: when Boolean(someOtherVar) is true: it returns "these are not the droids you are looking for...move along".

提交回复
热议问题