Difference between !! and ! in JavaScript

This question already has an answer here:

  • What is the !! (not not) operator in JavaScript? 31 answers

  • A single bang ( ! ) is used to negate a boolean.

    Double bang ( !! ) is used to coerce a truthy/falsey value to a boolean true or false.

    for example

    var x = 0; // a falsey value
    console.log(x); // logs 0
    console.log(!x)// logs true
    console.log(!!x)// logs false
    
    var y = "Hello world"; // a truthy value
    console.log(y); // logs "Hello world"
    console.log(!y)// logs false
    console.log(!!y)// logs true

    What is the !! (not not) operator in JavaScript?

    From the JS wiki on SO

    Regarding !! :

    "Coerces oObject to boolean. If it was falsey (eg 0, null, undefined, etc.), it will be false, otherwise, true."

    "It converts a nonboolean to an inverted boolean (for instance, !5 would be false, since 5 is a non-false value in JS), then boolean-inverts that so you get the original value as a boolean (so !!5 would be true)"

    "So !! is not an operator, it's just the ! operator twice."

    链接地址: http://www.djcxy.com/p/12664.html

    上一篇: 这是什么意思“return !! userId”

    下一篇: 区别! 和! 在JavaScript中