Last active
June 14, 2022 05:45
-
-
Save getify/11336871 to your computer and use it in GitHub Desktop.
JS scope/hoisting quiz
This file contains 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
// Without cheating by running the code, | |
// what do these 3 result in? | |
function foo(a) { | |
a(); | |
function a() { | |
console.log("yay"); | |
} | |
} | |
foo(); // ?? | |
foo( undefined ); // ?? | |
foo( function(){ console.log("bam"); } ); // ?? |
This is a nightmare.
yay
yay
yay
what happened is like the folllowing:
function foo(a) {
a = function() {
console.log('yay')
}
a();
}
yay
yay
yay
yay
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-This might sound weird but javascript is considering variable a to be "function" because it is defined as such in foo's function declaration.
-Now as to why function a() is able to return the output of console.log even though it is called before it is declared in function foo() is due to the fact that the JavaScript interpreter "looks ahead" to find all the declarations (it's called function hoisting. Check this link to know more:
http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html)