Skip to content

Instantly share code, notes, and snippets.

@lzhoucs
Last active August 29, 2015 14:25
Show Gist options
  • Save lzhoucs/9f747183e19e63ac00ed to your computer and use it in GitHub Desktop.
Save lzhoucs/9f747183e19e63ac00ed to your computer and use it in GitHub Desktop.
javascript variable scope demo

In the following example:

  • i is defined; j is undefined but declared; k is undeclared thus causing error;
  • indx is hoisted to the top of the function.
(function () {
  var i = 1;
  var j;
  console.log("i : " + i); // i : 1
  console.log("j : " + j); // j : undefined
  //console.log("k : " + k);// ReferenceError: k is not defined

  console.log("indx : " + indx);// indx : undefined
  
  for(var indx = 0; indx < 3; indx++){
    console.log("indx in for : " + indx);// indx in for : 0|1|2
  }

  console.log("indx after for : " + indx);// indx after for : 3

}())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment