Declaring variables inside or outside in a for-in loop

Having two options:

Option A:

var index;
for (index in myObject) {
  // Do something
}

Option B:

for (var index in myObject) {
  // Do something
}

I do not know if in option B the variable indexis updated every time in the cycle or only once.

+4
source share
2 answers

These two pieces of code do exactly the same thing (and this is the case in most languages ​​such as C, C ++ and C # among others). If the variable was updated at each iteration, then, following your logic, it will also be reinitialized and will constantly go through the same object. Your cycle will be endless.

, JavaScript, ; , , , .

var

SO

SO

@torazaburo:

( , , for, while if, let:

let var1 = 123;

, , , :

function letTest() {
    let x = 1;
    if (true) {
        let x = 2;  // different variable
        console.log(x);  // 2
    }
    console.log(x);  // 1
}

. ( ) .

+4

2016 , let:

for (let i = 0; i < max; i++) { }
     ^^^

, , .

-, let, i for, "" i .

-, , , i. , " , " (. ). , for, i.

for (let i = 0; i < 10; i++) {
  setTimeout(() => alert(i), i * 1000);
}

, ,

for (var i = 0; i < 10; i++) {
  (function(i) {
    setTimeout(() => alert(i), i * 1000);
  }(i));
}

, SO, .

+2

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


All Articles