If a value must be defined to true or false, based off the check off another value, are there any gotchas in doing :
!!someValue
Just a quick run against chrome’s engine gives:
boolCheck=function(someValue){
return !! someValue;
}
console.log(boolCheck()); //false
console.log(boolCheck(undefined)); //false
console.log(boolCheck(null)); //false
console.log(boolCheck(1)); //true
console.log(boolCheck({va:1})); //true
console.log(boolCheck("someTS")); //true
console.log(boolCheck(boolCheck)); //true
which SEEMS to work….
The
!operator always returns eithertrueorfalse, so assuming evaluation ofxcompletes normally,!!xis a boolean value that is the equivalent ofBoolean(x)whereBooleanis the EcmaScript builtin function.http://es5.github.com/#x11.4.9 says
http://es5.github.com/#x9.2 explains how ToBoolean works
The above table explains most of your examples, but it may not be obvious why
is
false. When you call a function with fewer actual arguments than formal parameters, the extra parameters have the valueundefinedand, as the table above shows!!undefinedisfalse.The intent is less clear than
Boolean(someValue), but it will work consistently across platforms and most experienced Javascript devs will recognize it.