For my understanding the unary !
operator performs implicit type conversions, and are sometimes used for type conversion.
So basically the !
operator converts its operand to a boolean and negates it.
Now:
!!x // Same as Boolean(x)
In fact:
!!'true' === Boolean('true') // true
So I am assuming both !!x
and Boolean(x)
perform the same action.
I would like to know:
- Do you know any caveats making my assumptions wrong?
- Which way should be preferred in term of good practice?
- Do you know any differences to be aware among different ECMAScript versions or Browser vendors?
!!
because it is less typing. Just bang bang and you are done. But some would say thatBoolean()
casting function is more human readable.!!'false' === true
because as far as I know strings with a value other than''
are always truevar k = 'hey you'; console.log(k === !!k);
will print "false". This is all about type, the point is to get a boolean value based on the content of the operand, which might be anything from a number to an arbitrary object.