Example of how to judge the validity of variables in JavaScript

Source: Internet
Author: User
The JavaScript language is not strictly designed, and sometimes it is easy to confuse people. For example, the effectiveness of this variable is determined.
Here are several examples:
To understand why the above results are obtained, you must first understand the different meanings of undefined and null in JavaScript.
Here is a conclusion from instructor Ruan Yifeng's blog:

Null and undefined are basically synonymous, with only slight differences.

Null indicates "no object", that is, there should be no value.Typical usage:

(1) as a function parameter, it indicates that the function parameter is not an object.

(2) serves as the end point of the object prototype chain.

Undefined indicates "missing value", that is, there should be a value, but it is not defined yet.Typical usage:

(1) the variable is declared, but when no value is assigned, it is equal to undefined.
(2) when calling a function, the required parameter is not provided. This parameter is equal to undefined.
(3) the object does not have an attribute assigned a value. The value of this attribute is undefined.
(4) when the function does not return a value, undefined is returned by default.
In Java, the if condition must use a boolean expression. Therefore, when JavaScript is used, it is also customary to think so. In fact, when null, undefined, 0, "", and false in JavaScript are used as conditions for if, they are considered false.

Therefore, when determining a variable, you can use the following methods:

1. Accurately determine whether a variable is undefined

2. Accurately determine whether a variable is null

3. Determine whether a variable is null or undefined.

4. Determine whether the value is valid. You can directly use the variable name in the if expression. I often use it to determine whether the value of an input box is valid (note: if the variable value is 0, it will be treated as invalid)

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.