Last active
February 1, 2017 12:20
-
-
Save rmnblm/5d3f66ce7a37dbc38bd452a23e7bc823 to your computer and use it in GitHub Desktop.
Hoisting and Scopes in ES6
This file contains hidden or 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 () { | |
l1 = 'STEP 1'; | |
console.log(l1); // Output: STEP 1 | |
if (true) { | |
console.log(l1); // Output: STEP 1 | |
var l1 = 'STEP 2'; // var isn't block-scoped, gets hoisted | |
console.log(l1); // Output: STEP 2 | |
} | |
console.log(l1); // Output: STEP 2 | |
if (true) { | |
// console.log(l1); // Uncaught ReferenceError: l1 is not defined (TDZ) | |
// because l1 is hoisted but uninitialised | |
let l1 = 'STEP 3'; // let is block-scoped | |
console.log(l1); // Output: STEP 3 | |
} | |
console.log(l1); // Output: STEP 2 | |
if (true) { | |
l1 = 'STEP 4'; | |
console.log(l1); // Output: STEP 4 | |
} | |
console.log(l1); // Output: STEP 4 | |
(function () { | |
console.log(l1); // Output: STEP 4 | |
})() | |
(function () { | |
console.log(l1); // undefined | |
// because l1 is hoisted inside the function and initialised | |
var l1 = 'STEP 5'; // var is function-scoped | |
console.log(l1); // Output: STEP 5 | |
})() | |
console.log(l1); // Output: STEP 4 | |
(function () { | |
// console.log(l1); // Uncaught ReferenceError: l1 is not defined (TDZ) | |
// because l1 is hoisted but uninitialised | |
let l1 = 'STEP 6'; // let is function-scoped | |
console.log(l1); // Output: STEP 6 | |
})() | |
console.log(l1); // Output: STEP 4 | |
(function () { | |
// console.log(l1); // Uncaught ReferenceError: l1 is not defined (TDZ) | |
// because l1 is hoisted but uninitialised | |
let l1 = 'STEP 6'; // let is function-scoped | |
console.log(l1); // Output: STEP 6 | |
if (true) { | |
// var l1 = 'STEP 7'; // Uncaught SyntaxError: Identifier 'l1' has already been declared | |
let l1 = 'STEP 7'; | |
console.log(l1); // Output: STEP 7 | |
} | |
console.log(l1); // Output: STEP 6 | |
})() | |
console.log(l1); // Output: STEP 4 | |
(function () { | |
console.log(l1); // Output: STEP 4 | |
l1 = 'STEP 8'; | |
console.log(l1); // Output: STEP 8 | |
})() | |
console.log(l1); // Output: STEP 8 | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment