Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created May 20, 2019 17:40
Show Gist options
  • Save shailrshah/14161352f7a5a246d5be0b2ac6a0df76 to your computer and use it in GitHub Desktop.
Save shailrshah/14161352f7a5a246d5be0b2ac6a0df76 to your computer and use it in GitHub Desktop.
Javascript Scope and Hoisting
// 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