JavaScript OR (||) variable assignment explanation

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

    This is made to assign a default value, in this case the value of y, if the x variable is falsy.

    The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

    The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

    For example:

    "foo" || "bar"; // returns "foo"
    false || "bar"; // returns "bar"
    

    Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

提交回复
热议问题