JavaScript single VAR statement

Source: Internet
Author: User

Using a unique VAR statement at the top of a function is a recommended pattern, and the benefits are:
1, you can find all the variables in the same place.
2. Avoid the logic errors generated by using the variable before the variable declaration.

JavaScript allows you to write any number of VAR statements anywhere in the function, but they behave like declaring variables at the top of the function body, which is called "declaration ahead," which can cause logic errors when you use this variable before declaring a statement.
For JavaScript, once a variable is declared within a scope (in the same function), the variable is present throughout the scope, including where it precedes the Var declaration statement.

  */  Not familiar with the assumption that the first alert is global and the second is local.    But the result is not so. * Analysis: The result of the first alert is not the ' global ' variable.    Since MyName is declared within a function, all the variable declarations in this scope are advanced to the top of the function * i.e. Var myname, although defined later in the statement, the result of the first alert is undefined;    * Therefore, to avoid similar procedural logic with "ambiguity", it is best to declare it together before use.  */  myname  = "global"; //     global variable  function   Func () {alert (myname);  //         "undefined"         var  myname = "local"  //  "local"   

3, you can be reminded to see whether the defined variables are local or global.
4, the amount of code less.


When you use a var to define multiple variables, separate them with commas, or you can initialize the variables directly.

function func () {        var  A,            B,            = a + b,            = {},            i;    }

JavaScript single VAR statement

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.