JavaScript OR (||) variable assignment explanation

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

    Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.

    f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:

    alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'
    

提交回复
热议问题