Created
February 21, 2015 14:06
-
-
Save eliza-abraham/aa0bd8538bcde8ac786c to your computer and use it in GitHub Desktop.
JavaScript Scopes & Hoisting
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
/* Scopes */ | |
// Ex: 1 | |
(function() { | |
var a = b = 5; | |
})(); | |
console.log(b); // 5, b is global without var. | |
// Strict Mode | |
(function() { | |
'use strict'; | |
var a = window.b = 5; | |
})(); | |
console.log(b); // 5 , without window.b will throw an error. | |
var global = 10; | |
function changeGlobal(){ | |
alert(global); | |
global = 20; | |
alert(global); | |
} | |
changeGlobal(); // 10 20 | |
/* Hoisting */ | |
// Example 1 // | |
var global = 10; | |
function changeGlobal(){ | |
alert(global); | |
var global = 20; | |
alert(global); | |
} | |
alert(global) | |
changeGlobal(); // 10 undefined 20 | |
// After hoisting | |
var global = 10; | |
function changeGlobal(){ | |
var global; | |
alert(global); // undefined | |
global = 20; | |
alert(global); // 20 | |
} | |
alert(global); // 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment