return !1 in javascript

2019-01-08 22:33发布

问题:

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 !1 or return !0

Could someone please explain what it means please?

Here is the function that I came across:

function convertStringToBoolean(a) {
    typeof a == "string" && (a = a.toLowerCase());
    switch (a) {
    case "1":
    case "true":
    case "yes":
    case "y":
    case 1:
    case !0:
        return !0;
    default:
        return !1
    }
}

Thanks In advance!

回答1:

return !1 means return false and return !0 - return true. In the specification - 11.4.9 Logical NOT Operator - when you place ! in front the result is evaluated as Boolean and it the opposite is returned.

Example:

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

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

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



回答2:

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



回答3:

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"