Isaac Lubow
Isaac Lubow

Reputation: 3573

Can JavaScript get confused between local variables?

If I have a pair of functions that both set local variables, for example, the variable i in common for loops, and one happens to be called while the other is running, is there any danger of namespace confusion?

Upvotes: 3

Views: 126

Answers (3)

Daniel Vassallo
Daniel Vassallo

Reputation: 344441

Keep in mind that JavaScript does not have block scope, but only function scope.

In addition, if you have nested loops, there will only be one i variable in the following example:

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
}

Douglas Crockford recommends that the var statements should be the first statements in the function body in Code Conventions for the JavaScript Programming Language:

JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.

I think he has a point, as you can see in the following example, which will not confuse readers into thinking that the variables i and j are held in the scope of the for loop blocks:

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
    }
  }
}

Upvotes: 11

Rahul
Rahul

Reputation: 1876

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

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630569

As long as you're using var, like this:

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

Then it's local and you're fine, if you don't use var, you have a global variable on your hands, and potential issues. Also if a for loop is nested in another, you should use a different variable name for each loop.

Upvotes: 4

Related Questions