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?

3

1 Answer 1

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 ); 
Sign up to request clarification or add additional context in comments.

5 Comments

I realize that. I had looked at this post initially stackoverflow.com/questions/784929/…. I am still curious if using this implementation is even necessary for this situation.
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.
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).
To add to Pointy's answer and comment, JavaScript has many truthy values, aside from 'true'. See stackoverflow.com/questions/1995113/strangest-language-feature/…
If you're casting to a boolean, it's more clear to use the boolean cast function Boolean(x);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.