Created
May 20, 2019 17:40
-
-
Save shailrshah/14161352f7a5a246d5be0b2ac6a0df76 to your computer and use it in GitHub Desktop.
Javascript Scope and Hoisting
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
// Scope - let and const have block scope. var has function scope. | |
if(true) {var x = 1; let y = 2; const z = 3;} | |
console.log(x); // 1 | |
console.log(y); // ReferenceError: y is not defined | |
console.log(z); // ReferenceError: z is not defined | |
let y = 2; | |
const z = 3; | |
y = 20; | |
z = 30; // TypeError: Assignment to constant variable. | |
console.log(y); // 20 | |
console.log(z); // 3 | |
// Variable Hoisting - Only for var, not let or const | |
(() => { | |
console.log(x === undefined); // true | |
console.log(y === undefined); // ReferenceError: y is not defined | |
var x = 3; | |
let y = 4; | |
})(); | |
var myvar = 'my value'; | |
(function() { | |
console.log(myvar); // undefined | |
var myvar = 'local value'; // myvar is hoisted in the begining of the function. So it's undefined at the start. | |
})(); | |
console.log(myvar) // 'my value' | |
// Function hoisting - function declarations get hoisted up, function expressions do not. | |
foo(); function foo() {console.log('bar');} // 'bar' | |
baz(); var baz = () => console.log('bar2'); // TypeError: baz is not a function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment