3

I can understand cases when you will want to convert an object value to a boolean and save it in a variable. However, I came across the following code in a jQuery template and was wondering if the !! (double exclamation operators) is even necessary.

{{if !!sectionId}}
    // do something...
{{/if}}

I am assuming that it is not since Javascript will automatically evaluate the expression following the if as boolean. Therefore, you could just write:

{{if sectionId}}
    // do something...
{{/if}}

Am I right in my assumption?

Vincent Catalano
  • 2,259
  • 4
  • 22
  • 29
  • Possibe duplicate: http://stackoverflow.com/questions/784929/what-is-the-operator-in-javascript – kieran Oct 26 '11 at 18:06
  • possible duplicate of http://stackoverflow.com/questions/784929/what-is-the-operator-in-javascript – jbabey Oct 26 '11 at 18:09
  • This is the most close duplicate IMO: [How to use the double not (!!) operator in javascript](http://stackoverflow.com/questions/2174297/how-to-use-the-double-not-operator-in-javascript) – Christian C. Salvadó Oct 26 '11 at 18:17

1 Answers1

8

There is no !! operator in JavaScript. There's just !. What you're seeing is a doubled application of that single operator.

A single application of ! will return a boolean by evaluating the "truthiness" of its argument, giving the boolean inverse of that. The second ! therefore gives the boolean inverse of that value, which is thus the boolean "truthiness" of the original value.

Personally I wouldn't use it in a simple if statement as in your example, but it's handy for APIs that might explicitly check for a boolean-typed parameter:

someAPI( !! someExpression );
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • I realize that. I had looked at this post initially http://stackoverflow.com/questions/784929/what-is-the-operator-in-javascript. I am still curious if using this implementation is even necessary for this situation. – Vincent Catalano Oct 26 '11 at 18:09
  • 3
    It's necessary when the code, for whatever reason, *really* needs a boolean value. Some APIs explicitly check for a boolean and not a truthy value in function argument lists etc. – Pointy Oct 26 '11 at 18:14
  • type security can be an issue, if you want to make sure a function returns a boolean, it can be important to cast: `return !!(this.foo || this.bar)` would be unnecessary in other languages, but `||` and `&&` don't actually return booleans, they just returns the first `truthy` and `falsey` values they come across (respectively). – zzzzBov Oct 26 '11 at 18:21
  • To add to Pointy's answer and comment, JavaScript has many truthy values, aside from 'true'. See http://stackoverflow.com/questions/1995113/strangest-language-feature/1998224#1998224 – Matt Oct 26 '11 at 18:21
  • 1
    If you're casting to a boolean, it's more clear to use the boolean cast function Boolean(x); – kybernetikos Dec 22 '11 at 19:11