JavaScript OR (||) variable assignment explanation

后端 未结 12 2400
北恋
北恋 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条回答
  •  -上瘾入骨i
    2020-11-21 06:47

    It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.

    var x = '';
    var y = 'bob';
    var z = x || y;
    alert(z);
    

    Will output 'bob';

提交回复
热议问题