Original: Http://www.cnblogs.com/fang9159/archive/2012/09/14/boolean.html (Invasion and deletion)
Recently interview more, but every time I ask this question, answer the classmate not many
var a = 0;if (a) { alert (1); }
Some people will answer alert (1), some people will not do it.
The result is not executed, but do not perform the classmate also say why, he will only say with his experience, so here I think it is necessary to fill the basic JS, JS basic Good people can skip this blog post.
First of all, let's recall the Boolean () before we begin.
Boolean is a transformation function. That is, you can pass any value to a Boolean type, which returns True and false.
Then when is true, when is false, it has a certain rule.
I use a table to indicate this rule.
Data type |
The value converted to true |
Value converted to False |
Boolean |
True |
False |
String |
Any non-empty string |
“” |
Number |
Any value other than 0 |
0 and Nan |
Object |
Any object |
Null |
Undefined |
|
Undefined |
Note: Undefined does not have a value converted to true.
From here we are at a glance, and a Boolean (0) returns false;
Then if there is no expression inside the IF statement, just a value such as if (XXX) it will automatically perform a Boolean (XXX) operation, that is, if (XXX) = if (Boolean (XXX))
So we correspond to the above Boolean conversion rules, and then combine the above questions, it is very easy to understand.
This is the reason that if (0) returns false.
"Reprint" JS basis: About Boolean () and if