Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any point of using "return !0" in javascript?

If you go to a google result page, and run rwt.toString(), you'll see that the return call for this function is:

return !0; 

I can't think of any reason why this wouldn't always be true. Is this just a shorthand for true, or is there more going on here?

like image 682
Darth Egregious Avatar asked Jan 05 '12 21:01

Darth Egregious


People also ask

What does return 0 do in JS?

Returning 0 from main tells the operating system that the program executed successfully. Every value has a different meaning but all in all, a non-zero value returned from main() means unsuccessful execution of the program.

Is return necessary in JavaScript?

No, a return statement is not necessary at the end of a void function (sorry for the C-terms there). If you want to exit a function early, however (say if a specific condition wasn't met), then you'll use a return statement, even if you're not returning a value.

Is 0 a value in JavaScript?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

What does return 0 and 1 mean in JavaScript?

Answer Wiki. It means ‘return 0 (or 1) from the current function’. What 0 and 1 “mean” in this case is dependent on what you expect they mean. JavaScript considers some values (0 among them) to be “falsy” (i.e., in the context where a boolean value is expected, they would do what the value false would do), and others (like 1) to be “truthy”.

How do you return a value from a JavaScript function?

JavaScript return The return statement is used to return a particular value from the function to the function caller. The function will stop executing when the return statement is called. The return statement should be the last statement in a function because the code after the return statement will be unreachable.

What is a return statement in JavaScript?

Definition and Usage. The return statement stops the execution of a function and returns a value from that function. Read our JavaScript Tutorial to learn all you need to know about functions.

What is return 0 in PHP?

return 0; at the end of functions that don't return a value. This isn't used in PHP, because if a function is doesn't have a return, a value NULL is automatically returned.


1 Answers

It is always true, but it takes 2 bytes to download (!0 is 2 characters) instead of 4 bytes to download the boolean value true.

Most Javascript minifiers will convert true to !0 and false to !1. You can see an example of this by typing var y = true; with Simple optimizations on Google's Closure Compiler: http://closure-compiler.appspot.com/home

like image 55
Paul Avatar answered Oct 06 '22 00:10

Paul