Last active
November 30, 2018 10:56
-
-
Save kamlekar/908d0a997ec66c6e35b602cbf4e3cc25 to your computer and use it in GitHub Desktop.
Classic problem of hoisting.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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