In the context of if
statements I'm with you, it is completely safe because internally, the ToBoolean
operation will be executed on the condition expression (see Step 3 on the spec).
But if you want to, lets say, return a boolean value from a function, you should ensure that the result will be actually boolean, for example:
function isFoo () {
return 0 && true;
}
console.log(isFoo()); // will show zero
typeof isFoo() == "number";
In conclusion, the Boolean Logical Operators can return an operand, and not a Boolean
result necessarily:
The Logical AND operator (&&
), will return the value of the second operand if the first is truly:
true && "foo"; // "foo"
And it will return the value of the first operand if it is by itself falsy:
NaN && "anything"; // NaN
0 && "anything"; // 0
On the other hand, the Logical OR operator (||
) will return the value of the second operand, if the first one is falsy:
false || "bar"; // "bar"
And it will return the value of the first operand if it is by itself non-falsy:
"foo" || "anything"; // "foo"
Maybe it's worth mentioning that the falsy values are: null
, undefined
, NaN
, 0
, zero-length string, and of course false
.
Anything else (that is not falsy, a Boolean
object or a Boolean
value), evaluated in boolean context, will return true
.
Any falsy value will satisfy the if(!insert_variable_here)
condition, including:
false
null
undefined
- The empty string
''
- The number
0
NaN
If callback
return evaluates any of those values, the condition will be satisfied.
Even though null != false
, the following will give you an alert:
x = null;
if(!x) {
alert('"!null" does evaluate to true');
}
Regardless of whether or not null != false
makes sense to you or anyone else, the point is that in JavaScript null
is a falsy value, and thus a value that would satisfy the condition in my first bit of code listed above. This, it seems, is the question you have asked--not, rather, if null
should or should not == false
.
Best Answer
It converts
Object
toboolean
. If it was falsy (e.g.,0
,null
,undefined
, etc.), it would befalse
, otherwise,true
.So
!!
is not an operator; it's just the!
operator twice.It is generally simpler to do:
Real World Example "Test IE version":
If you ⇒
But if you ⇒