james james -4 years ago 63
Javascript Question

Local and global variables in loops

I know basics about local and global variables, but could anybody explain difference between these two examples of code?

var elements = document.querySelectorAll('.classname');
for (var i = 0; i < elements.length; i++) {
// do something
}


and

var elements = document.querySelectorAll('.classname');
for (i = 0; i < elements.length; i++) { // <-- removed "var" before "i = 0"
// do something
}

Answer Source

With the var keyword, there is no "block" scope, so declarations are either "function" scoped or "global". The fact that you declare a variable in a loop or in a true/false branch of an if statement does not create a variable scoped to just that block of code. This is quite different than in most compiled languages.

ECMAScript 2016 (a.k.a. ES6) introduces "block" scope with the let keyword.

So, if you omit the var keyword and just create a new variable in a function, that variable becomes global because the JS runtime doesn't know where you wanted it scoped to.

Here's some examples:

// Outside of functions, the var keyword creates global variables
var g = "global";

function foo(){
  // Inside of functions, the var keyword creates "local" or function scoped variables
  var l = "local";
  
  // But, omitting the "var" keyword, whereever you do it, creates a global
  oops = "global";
  
  // But, creating a function scoped variable of the same name as a variable in a higher
  // scope, just hides the one from the higer scope as long as the code runs in the smaller
  // scope:
  var g = "local";

  // Other than global and function, the var keyword does not create "block" scope:
  if(true){
    var x = "surprise!";
  }
  
  // Now, we'll see what we get when we are in the local scope:
  console.log(g);     // "local", not "global" because smaller scope prevails 
  console.log(l);     // "local";
  console.log(oops);  // "global"
  console.log(x);     // "surprise!" because x has function scope, not block

}

foo();

  // Now, we'll see what is available back in the global scope:
  console.log(g);         // "global" because now we are in the global scope
  console.log(typeof l);  // It's an error to try to access directly, type is undefined
  console.log(oops);      // "global" because we omitted var and it became global
  console.log(typeof x);  // It's an error to try to access directly, type is undefined

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download