JavaScript OR (||) variable assignment explanation

后端 未结 12 2414
北恋
北恋 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:55

    Its called Short circuit operator.

    Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.

    It could also be used to set a default value for function argument.`

    function theSameOldFoo(name){ 
      name = name || 'Bar' ;
      console.log("My best friend's name is " + name);
    }
    theSameOldFoo();  // My best friend's name is Bar
    theSameOldFoo('Bhaskar');  // My best friend's name is Bhaskar`
    

提交回复
热议问题