Skip to content

Instantly share code, notes, and snippets.

@eliza-abraham
Created February 21, 2015 14:06
Show Gist options
  • Save eliza-abraham/aa0bd8538bcde8ac786c to your computer and use it in GitHub Desktop.
Save eliza-abraham/aa0bd8538bcde8ac786c to your computer and use it in GitHub Desktop.
JavaScript Scopes & Hoisting
/* 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