Proper way to set a function's default parameter to a boolean?

前端 未结 2 1227
感动是毒
感动是毒 2021-01-28 10:59

I\'ve a function read() that takes as a boolean paramater. If false is passed in - read(false) - it shouldn\'t run a block of code. It wo

2条回答
  •  猫巷女王i
    2021-01-28 11:04

    If you're expecting falsey values, use typeof:

    var x = typeof x !== 'undefined' ? x : false;
    

    Otherwise, if you do this:

    var x = x || true;
    

    And pass in false, the value of x will be true.

提交回复
热议问题