Where should I put the Circular Variable declaration in Javascript?

Source: Internet
Author: User

Where should I put the Circular Variable declaration in Javascript?

Do not take any details away. I believe that many Javascript developers have forgotten where var I Should Be When declaring cyclic variables: What is the impact on the running of the program when I put them in different positions? Which method complies with the Javascript language specifications? Which method matches the future development direction of the ecma standard? This article will analyze and compare the four common writing methods for declaring cyclic variables.

 

Habit 1: do not declare direct use

 
 
  1. function loop(arr) { 
  2.     for (i = 0; i < arr.length; i++) { 
  3.         // do something 
  4.     } 

It is a very dangerous habit to use. In general, the cyclic variable will become an attribute on the window object and be used globally. It is very likely to affect the normal logic implementation of the program, I will not go into details here.
Note that in strict mode, the usage of direct value assignment without declaring variables will directly throw an exception. It is time to do so! Reference a paragraph in appendix C of the ecma-262 standard:
"Assignment to an undeclared identifier or otherwise unresolvable reference does not create a property in the global object. when a simple assignment occurs within strict mode code, its LeftHandSide must not evaluate to an unresolvable Reference. if it does a ReferenceError exception is thrown (6.2.3.2 )."
In other words, if undeclared variables are used, the ReferenceError exception will be thrown.

Habit 2: place the statement block in the for loop and declare it repeatedly

 
 
  1. function loop(arr) { 
  2.     for (var i = 0; i < arr.length; i++ ){ 
  3.         // do someting 
  4.     } 
  5.     // console.log(i); 
  6.     for (var i = 0; i < arr.length; i++ ){ 
  7.         // do something else 
  8.     } 

This method seems to be the most secure specification. Many developers who have switched from C and Java to frontend development prefer this method. In fact, this may be caused by misunderstanding of an important concept in Javascript-variable scope. Unlike C and Java, Javascript does not have a real block-level scope, that is, after the first loop ends, console. log (I) Does not print undefined or throw a ReferenceError exception, but prints the arr normally. length.
However, this method is of little significance except for appearance, however, it has long been compatible and does not violate any Regulations-The ecma standard does not prohibit repeated declarations of the same variable in a specific scope. In addition, there is another good news. In ECMAScript 6, A New Keyword -- let appears to support the true block-level scope. Here is a portal. If you are interested, you can learn about it on your own:
Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Habit 3: define them together with other variables at the top of the Function

 
 
  1. function loop(arr) { 
  2.     var var1; 
  3.     var var2; 
  4.     var i; 
  5.  
  6.     for (i = 0; i < arr.length; i++) { 
  7.         // do something 
  8.     } 

This c89-like-style variable definition method is almost impeccable in Javascript, neither causing misunderstanding of Javascript support block-level scope, nor polluting the entire scope, nor violating any standards and specifications, the main drawback is that the declaration of the cyclic variables and the cyclic bodies may be separated far away. Without using more code, apart from waiting for major browser vendors to implement the let keyword in ECMAScript 6, this problem does not seem to find a better solution.

Habit 4: encapsulate loop code into IIFE

 
 
  1. function loop(arr) { 
  2.     (function () { 
  3.         for (var i = 0; i < arr.length; i++) { 
  4.             // do something 
  5.         } 
  6.     })(); 
  7. }

The last habit is that front-end programmers are familiar with IIFEImmediately-Invoked Function Expression), that is, to execute functions immediately. The main disadvantage of this method is that it is relatively difficult to write, and there is a small amount of excess performance loss), but it is good in compatibility and compliance with various standards and specifications. If it is not too troublesome, developers can adopt this method.

The above is a brief introduction and analysis of four common cyclic variables in Javascript to define writing habits. Each has its own advantages and disadvantages. Readers can choose the best choice based on their own needs. It should be said that there was no perfect solution to define cyclic variables before ECMAScript 6. Fortunately, the ECMAScript Standards Committee also promptly discovered this issue. let's look forward to the let keyword together.

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.