I've just walked into this code:
val.enabled = !!enable
and have no idea what does "!!" do... I googled JavaScript operators but haven't found this one.
I've just walked into this code:
val.enabled = !!enable
and have no idea what does "!!" do... I googled JavaScript operators but haven't found this one.
!!
converts the value to the right of it to its equivalent boolean value. (Think poor man's way of "type-casting"). Its intent is usually to convey to the reader that the code does not care what value is in the variable, but what it's "truth" value is.
It's a horribly obscure way to do a type conversion.
! is NOT. So !true is false and !false is true. !0 is true and !1 is false.
So you're converting a value to a bool, then inverting it, then inverting it again.
//Maximum Obscurity:
val.enabled = !!userId;
//Partial Obscurity:
val.enabled = (userId != 0) ? true : false;
//And finally, much easier to understand:
val.enabled = userId != 0;
It's a double not
operation. The first !
converts the value to boolean and inverts its logical value. The second !
inverts the logical value back.
! is "boolean not", which essentially typecasts the value of "enable" to its boolean opposite. The second ! flips this value. So, !!enable
means "not not enable," giving you the value of enable
as a boolean.
!!foo
applies the unary not operator twice and is used to cast to boolean type similar to the use of unary plus +foo
to cast to number and concatenating an empty string ''+foo
to cast to string.
Instead of these hacks, you can also use the constructor functions corresponding to the primitive types (without using new
) to explicitly cast values, ie
Boolean(foo) === !!foo
Number(foo) === +foo
String(foo) === ''+foo
It's not a single operator, it's two. It's equivalent to the following and is a quick way to cast a value to boolean.
val.enabled = !(!enable);