JavaScript OR (||) variable assignment explanation

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

    It's setting the new variable (z) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.

    For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:

    function doSomething(data, callback) {
        callback = callback || function() {};
        // do stuff with data
        callback(); // callback will always exist
    }
    

提交回复
热议问题