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

前端 未结 2 1221
感动是毒
感动是毒 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条回答
  • 2021-01-28 11:03

    It's because the concept automatic conversion in Javascript, the undefined value convert to false. So three lines are similar to ensure the variable first_time_here is false, not undefined.

    if first_time_here is undefined:

    first_time_here = undedined !== false -> first_time_here = false != false
    -> first_time_here = false;
    

    And:

    first_time_here = undedined || false -> first_time_here = false || false
    -> first_time_here = false;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题