Given the following code:
if ("string") {
console.log('true!');
}
//logs "true" to the console
if ("string"==true) {
console.log('true!');
}
//doesn't log anything
Why does this happen? I thought "string"
was being cast to a number, as is the boolean. So true
becomes 1
, and "string"
becomes NaN
. The second if statement makes sense, but I don't see why the first statement causes the inner loop to be evaluated. What's going on here?
Best Answer
It is being cast to Boolean. Any non-empty string evaluates to true.
From the ECMAScript Language Specification:
As far as the
==
operator is concerned, it's complicated, but the gist of it is that if you compare a number to a non-number the latter is converted into a number. If you compare a boolean against a non-boolean, the boolean is first converted to a number, and then the previous sentence applies.See section 11.9.3 for details.