Reputation: 1516
I have just come across a function in JavaScript which has return !1
.
What does this actually mean? Why would you return !1
or return !0
?
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
}
}
Upvotes: 21
Views: 11144
Reputation: 23
Here the code it is verifying:
"case 1", "case true", "case yes", "case y", "Case 1"
"case !0"
return "true"
Upvotes: -4
Reputation: 19492
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.
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.
Upvotes: 23
Reputation: 120498
This seems to be a particularly silly way of returning true
or false
Upvotes: 11