Skip to content

Instantly share code, notes, and snippets.

@getify
Last active June 14, 2022 05:45
Show Gist options
  • Save getify/11336871 to your computer and use it in GitHub Desktop.
Save getify/11336871 to your computer and use it in GitHub Desktop.
JS scope/hoisting quiz
// 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"); } ); // ??
@nrum
Copy link

nrum commented Nov 3, 2017

  1. foo(); //yay
  2. foo( undefined ); //yay
  3. foo( function () { console.log("bam"); } ); //yay

@FarisMarouane
Copy link

Could you please explain why ?

@reynold666
Copy link

-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)

@scorbajio
Copy link

This is a nightmare.

@WangNingning1994
Copy link

yay
yay
yay

@WangNingning1994
Copy link

what happened is like the folllowing:

function foo(a) {
  a = function() {
    console.log('yay')
  }
   a();
}

@abishegaTemenos
Copy link

yay

@rizwankhan5174
Copy link

yay
yay
yay

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