Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return !1 in javascript

Tags:

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!

like image 848
DarkMantis Avatar asked Nov 24 '11 10:11

DarkMantis


People also ask

What does return 1 do in JavaScript?

return ! 1 is equivalent to return false.

What is return () in JavaScript?

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 does return 0 do in JS?

return 0 in the main function means that the program executed successfully. return 1 in the main function means that the program does not execute successfully and there is some error. return 0 means that the user-defined function is returning false.

What does '$' mean in JavaScript?

Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.


2 Answers

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.

like image 61
Bakudan Avatar answered Sep 21 '22 08:09

Bakudan


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

like image 36
spender Avatar answered Sep 25 '22 08:09

spender