How to determine whether a variable is undefined

Source: Internet
Author: User

Original http://www.quora.com/JavaScript/What-is-the-best-way-to-check-if-a-property-or-variable-is-undefined

1. Javascript determines the variable type based on the value. The value can be undefined. However, variables can only be declared or not declared.

2. Once declared, the variable is initialized to the undefined value until it is assigned another value.

3. Declared variables do not have undefined values. They do not exist at all. Referencing a nonexistent variable will throw a ReferenceError exception unless you are using the typeof operator.

4. the typeof operator will return undefined for the following two variables: undefined variables that are not declared, and variables that are clear but not assigned values.

5. null = undefined, but null! = Undefined. The double equal sign implicitly calls type conversion.

6. Do not try to compare variables with undefined. Undefined is not a Javascript keyword. So if undefined is redefined, the comparison you expect will become invalid. (Of course, you can declare a variable named "undefined" in the local scope, so "undefined" is undefined)

7. For object-type variables, undefined will be returned if no declared attribute is accessed. If a call (calling) has no declared sub-method, an exception will be thrown. However, if it is only an access (accessing), no exception will be thrown (as long as the object exists ).

8. Because of the relationship between vertices (4), using only the typeof operator is not enough to distinguish between a variable that has not been declared and a variable that has not been assigned a value. We can use the in operator or the Object. hasOwnProperty () method, which filters out the attributes of the parent node inherited from the prototype chain.

To sum up, the simplest way to check undefined is to use the typeof operator.

 

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.