Skip to content

Instantly share code, notes, and snippets.

@kamlekar
Last active November 30, 2018 10:56
Show Gist options
  • Save kamlekar/908d0a997ec66c6e35b602cbf4e3cc25 to your computer and use it in GitHub Desktop.
Save kamlekar/908d0a997ec66c6e35b602cbf4e3cc25 to your computer and use it in GitHub Desktop.
Classic problem of hoisting.
var foo = 1;
function bar(){
if(!foo){
var foo = 10;
}
alert(foo);
}
bar();
// HOISTING
// Converts to
function bar(){
var foo; // local scope foo
if(!foo){ // considers local scope foo
foo = 10;
}
alert(foo); // gives value of local scope foo i.e 10
}
var foo; // defines global scope foo
foo = 1; // assign value to global scope foo
bar(); // call the function, gives value of local scope foo i.e 10
// alert(foo); => gives value of global scope foo i.e 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment