Can JavaScript get confused between local variables?

If I have a couple of functions that set local variables, like a variable iin common loops for, and one of them is called while the other is running, is there any danger of namespace confusion

+3
source share
3 answers

While you are using var, for example:

for(var i = 0; i < something; i++)

Then it is local, and you are fine, if you are not using var, you have a global variable on your hands and possible problems. In addition, if the cycle is fornested in another, you must use a different variable name for each cycle.

+4
source

, JavaScript , .

, , i:

function myFunction() {
  for (var i = 0; i < 10; i++) {
    for (var i = 0; i < 10; i++) {
      // code here will run 10 times instead of 100 times
    }
  }
  // variable i is still accessible from here
}

, var JavaScript:

JavaScript , , C. .

, , , , i j for:

function myFunction() {
  var i, j;    // the scope of the variables is now very clear
  for (i = 0; i < 10; i++) {
    for (j = 0; j < 10; j++) {
      // code here will run 100 times
    }
  }
}
+11

This will be a problem if you are referring to nested loops. Each time you enter a second loop, the value of i (previously set in the outer loop) will be reset.

0
source

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


All Articles