JavaScript OR (||) variable assignment explanation

后端 未结 12 2413
北恋
北恋 2020-11-21 06:41

Given this snippet of JavaScript...

var a;
var b = null;
var c = undefined;
var d = 4;
var e = \'five\';

var f = a || b || c || d || e;

alert(f); // 4
         


        
12条回答
  •  不知归路
    2020-11-21 06:49

    It means that if x is set, the value for z will be x, otherwise if y is set then its value will be set as the z's value.

    it's the same as

    if(x)
      z = x;
    else
      z = y;
    

    It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.

提交回复
热议问题