return !1 in javascript

前端 未结 3 1705
梦如初夏
梦如初夏 2020-11-29 05:20

I have just come across a function in javascript which has return !1

I was just wondering what this actually meant?

Why would you return !

相关标签:
3条回答
  • 2020-11-29 05:46

    In immediate response to your question:

    • return !1 is equivalent to return false
    • return !0 is equivalent to return true

    In the specification - 11.4.9 Logical NOT Operator - it states that when you place an exclamation mark ! in front, the result is evaluated as Boolean and the opposite is returned.

    Example:

    var a = 1, b = 0;
    var c = a || b;
    alert("c = " + c + " " + typeof c); // here typeof c will be "number"
    
    a = !0, b = !1;
    c = a || b;
    alert("c = " + c + " " + typeof c); // here typeof c will be "boolean"
    

    I mostly see this in a code passed through Google's JS optimiser. I think it is mostly done to achieve shortness of the code.

    It is often used when a strictly Boolean result is needed - you may see something like !!(expression). Search in jQuery, for example.

    0 讨论(0)
  • 2020-11-29 05:49

    This seems to be a particularly silly way of returning true or false

    0 讨论(0)
  • 2020-11-29 06:11

    Here the code is verifying :

    • to return nothing or do nothing on these cases : "case 1", "case true", "case yes", "case y", "Case 1"
    • and when the case is : "case !0" return "true"
    • when none of the above cases are been satisfied by default it returns "false"
    0 讨论(0)
提交回复
热议问题