javascript - What is the difference between !!variable and variable -
this question has answer here:
i have seen developers use variables in way not make sense me, , have seen more commonly in angularjs.
consider code:
var somevariable = (someothervariable === 'true'); if (!!somevariable) { // stuff here }
why not leave out 2 exclamation marks? not same? benefit of doing this?
the double not operator !!
coerces (potentially non-boolean) value boolean.
in specific example:
var somevariable = (someothervariable === 'true'); if (!!somevariable) { // stuff here }
somevariable
guaranteed boolean (since result of ===
comparison boolean) coercing boolean not change operation in way , pretty wasted code. if wasn't boolean, don't need coerce boolean test if (somevariable)
either there's yet reason not use !!
here.
when !!
useful when want store true boolean somewhere, may have truthy or falsey value, not true boolean. can coerce boolean !!
.
so, suppose had value not boolean , wanted set other value true boolean based on truthy-ness or falsey-ness of first variable. this:
var myvar; if (somevar) { myvar = true; } else { myvar = false; }
or this:
myvar = somevar ? true : false;
or this:
myvar = !!somevar;
Comments
Post a Comment