Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the !! operator even necessary in Javascript?

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?

like image 986
Vincent Catalano Avatar asked May 22 '26 19:05

Vincent Catalano


1 Answers

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 );
like image 130
Pointy Avatar answered May 24 '26 10:05

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!