Correct for declaring a variable /

What is the correct syntax for declaring a loop-dependent variable in a for / in loop?

The first two both seem to work (and don't raise flags in the Google Closure Compiler), but only the third passes Crockford JS Lint. I do not want to use it, mainly because it is not compact.

JSLint complains that either val is a bad variable (when I don't add var ), or that the declaration needs to be moved.

Are there any disadvantages for the first or second option? What should i use? (It is assumed that str is a declared string, and vals is a declared object)

1. No declaration:

 for(val in vals) { if(vals.hasOwnProperty(val)) { str += val; } } 

2. In the `for 'var declaration:

 for(var val in vals) { if(vals.hasOwnProperty(val)) { str += val; } } 

3. Outside of the var loop declaration:

 var val; for(val in vals) { if(vals.hasOwnProperty(val)) { str += val; } } 
+4
source share
3 answers

Remember to ignore JSLint. This guide is more than anything else. 2nd and 3rd are functionally identical, feel free to use (I use 2nd). The first one provides the global variable "val", so don't do this :)

The FYI argument behind the third is that declaring embedded variables is much harder to detect / find than:

 var a, b, c, d, e; 

at the top of the function.

+3
source

In addition to cwolves arguing for declaring a variable, JSLint also considers switching variables .

However, I prefer option number 2 when recording for cycles. However, I define the rest of my variables at the top of the function. I like:

 function foo(a) { var b, c = {d: "e", f: "g"}; for (var i = 0, j = a.length; i < j; i += 1) { ... } for (var h in c) { if (c.hasOwnProperty(h)) { ... } } } 
+1
source

1. Option

The variable val becomes an implicit global variable. Implicit global variables are 100% bad and should be avoided.

2. and 3. Option

The variable val becomes the variable of the contained region. If your code is inside a function, then the variable val becomes the local variable of this function. Both options are equivalent. (I prefer option 2.)

JSLint will throw because Crockford's idea is to always declare all variables at the top of the code. This is more important for a larger code size (for example,> 100 lines) - in this case, you might consider moving declarations from the for and in statements and putting them at the beginning of the code. This way you will have a good overview of all local variables.

+1
source

Source: https://habr.com/ru/post/1345611/


All Articles