Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abrjagad/d97bb9c1a09df7f9282e to your computer and use it in GitHub Desktop.
Save abrjagad/d97bb9c1a09df7f9282e to your computer and use it in GitHub Desktop.
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
//Using the code above, the browser will alert "1".
//I'm still unsure why it returns "1".
//Function hoisting means that functions are moved to the top of their scope. That is,
function b() {
a = 10;
return;
function a() {}
}
//will be rewritten by the interpeter to this
function b() {
function a() {}
a = 10;
return;
}
//Weird, eh?
//Also, in this instance,
function a() {}
//behaved the same as
var a = function () {};
//So, in essence, this is what the code is doing:
var a = 1; //defines "a" in global scope
function b() {
var a = function () {}; //defines "a" in local scope
a = 10; //overwrites local variable "a"
return;
}
b();
alert(a); //alerts global variable "a"
function test() {
foo(); // TypeError "foo is not a function"
bar(); // "this will run!"
var foo = function () { // function expression assigned to local variable 'foo'
alert("this won't run!");
}
function bar() { // function declaration, given the name 'bar'
alert("this will run!");
}
}
test();
// both the functions are same
//http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
function foo() {
if (false) {
var x = 1;
}
return;
var y = 1;
}
function foo() {
var x, y;
if (false) {
x = 1;
}
return;
y = 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment