Last active
August 29, 2015 14:15
-
-
Save abrjagad/d97bb9c1a09df7f9282e to your computer and use it in GitHub Desktop.
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
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" |
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
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(); |
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
// 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