Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

function - return !1 in javascript

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...