Improved understanding of js variables and deep understanding of js Variables

Source: Internet
Author: User

Improved understanding of js variables and deep understanding of js Variables

The Function Definition of JavaScript has a feature. It first scans the statements of the entire function body and "promotes" all declared variables to the top of the function:

'Use strict '; function foo () {var x = 'hello,' + y; alert (x); var y = 'bob';} foo ();

Although it is in strict mode, the statement var x = 'hello, '+ y; does not report an error because the variable y is declared later. However, alert displays Hello and undefined, indicating that the value of variable y is undefined. This is because the JavaScript engine automatically promotes the declaration of variable y, but does not increase the value assignment of variable y.

For the above foo () function, the JavaScript engine sees the code equivalent:

Function foo () {var y; // declare var x = 'hello, '+ y; alert (x); y = 'bob ';}

Because of this weird "feature" of JavaScript, when we define variables in a function, strictly abide by the rule "declare all variables in the function first. The most common practice is to use a var statement to declare all the variables used in the function:

Function foo () {var x = 1, // x is initialized to 1 y = x + 1, // y is initialized to 2 z, I; // The z and I are undefined // other statements: for (I = 0; I <100; I ++ ){...}}

The above js variable is a deep understanding of all the content shared by the editor. I hope you can give us a reference and support the help house.

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.