The use of the triple exclamation mark

前端 未结 5 813
眼角桃花
眼角桃花 2020-12-01 05:52

Looking through the source code of one of our projects, I\'ve found some amount of places where we\'re using three exclamation marks in conditional statements, like so:

相关标签:
5条回答
  • 2020-12-01 06:21

    In javascript, it's a way to show that what you are evaluating is not a boolean but a truthy or falshy.

    So for truthy/falshy values you either use !! or !!! and for booleans ! or nothing.

    This is simply for readability.

    0 讨论(0)
  • 2020-12-01 06:28

    It is the same as one exclamation mark. The key idea behind it is to improve visibility for the programmer. Compiler will optimize it as single '!' anyway.

    0 讨论(0)
  • 2020-12-01 06:35

    There is no difference between !a and !!!a, since !!!a is just !!(!a) and because !a is a boolean, !!(!a) is just its double negation, therefore the same.

    0 讨论(0)
  • 2020-12-01 06:40

    Consider:

    var x;
    console.log(x == false);
    console.log(!x, !x == true);
    console.log(!!x, !!x == true, !!x == false);  
    

    ... the console output is:

    false 
    true true 
    false false true
    

    notice how, even though x is "falsey" in the first use, it is not the same as false.

    But the second use (!x) has an actual boolean - but it's the opposite value.

    So the third use (!!x) turns the "falsey" value into a true boolean.

    ...with that in mind, the third exclamation point makes a TRUE negation of the original value (a negation of the "true boolean" value).

    ETA:

    OMG! I can't believe I didn't notice that this is a TRIPLE exclamation point question! Even after it was specifically pointed out to me.

    So, while my answer is hopefully useful to someone, I have to agree with the others who have posted that a triple-exclamation is functionally the same as a single.

    0 讨论(0)
  • 2020-12-01 06:43

    The first double exclamation marks turned to a boolean value any falsy value of the object (undefined, null, 0) or any truthy value, then the third one negates it.

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