JavaScript Boolean () and if learning notes

Source: Internet
Author: User

More recent interviews, but every time I asked this question, the answer came out of the students are not many

   
    
   
The code is as follows Copy Code
var a = 0;

 if (a) {
     alert (1);  
}
Some people will answer alert (1) and some will not do so.

The result is not carried out, but should not carry out the students can not say why, he will only say with his experience, so here I think it is necessary to make up the basic knowledge of JS, JS basic Good People may skip this blog.

First of all, let us recall the Boolean ();

Boolean is a transformation function. That is, you can pass any value to a Boolean type, which returns True and false.

So when is true and when is false, it has a certain rule.

I use a table to show this rule.

Data type Value converted to True The 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, Boolean (0) returns false;

So when there is no expression inside an if statement, just a value such as if (XXX) it automatically performs a Boolean (XXX) operation, that is, if (XXX) = if (Boolean (XXX))

So we correspond to the above Boolean conversion rules, combined with the above questions, it is very easy to understand.

This is why if (0) returns false.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.