Reputation: 12990
I have seen JS code written using
if(!!a){
//something here
console.log('something');
}
I don't understand what the preference of doing this is compared to:
if(a){
//something else here
console.log('something else here');
}
Do you gain anything by typing !!
in the expression with JS?
Upvotes: 1
Views: 80
Reputation: 3042
Some samples to understand :
var el = document.getElementById('el');
var log = function(val){
// el.innerHTLM+='<div><pre>' + JSON.stringify(val , null , ' ') +'<\pre></div>';
el.innerHTML+='<div><pre>' + val +'<\pre></div>';
};
var a = 'Helo';
log('a = ' + a);
log('! a = ' + ! a);
log(' !! a = ' + !!a );
log('---');
log('true =' + true);
log('!true =' + !true);
log('!!true =' + !!true);
log('---');
log('false =' + false);
log('!false =' + !false);
log('!!false =' + !!false);
log('---');
log('null =' + null);
log('!null =' + !null);
log('!!null =' + !!null);
log('---')
log('undefined =' + undefined);
log('!undefined =' + !undefined);
log('!!undefined =' + !!undefined);
log('0 =' + 0);
log('!0 =' + !0);
log('!!0 =' + !!0);
log('---');
log('1 =' + 1);
log('!1 =' + !1);
log('!!1 =' + !!1);
log('---');
log('[] =' + []);
log('![] =' + ![]);
log('!![] =' + !![]);
log('---');
log('{} =' + {});
log('!{} =' + !{});
log('!!{} =' + !!{});
<div id='el'>Use case:</div>
Upvotes: 0
Reputation: 113866
The if
statement checks for the truthiness of the expression passed to it. The !!
coerces truthiness into boolean. Therefore doing:
if (!!a) {}
is exactly the same as:
if (a) {}
This smells strongly of cargo-cult programming or influence form another language.
Upvotes: 2
Reputation: 48807
It's about truthy and falsy:
Everything in JavaScript has an inherent Boolean value, generally known as either truthy or falsy.
The following values are always falsy:
- false
- 0
- ""
- null
- undefined
- NaN
All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.
In your case, I don't think it is useful, since an if
already uses the truthy/falsy value of the condition:
if (0) {
// this will never be executed
}
The !!
can be used like this:
return !!myObject.length; // returns true if myObject.length > 0, false otherwise
Upvotes: 2