...
/ES2015 Scope & Hoisting - let & const
ES2015 Scope & Hoisting - let & const
We'll learn how the new keywords 'let' and 'const' eliminate the problems of variable hoisting, scope limitations, and unintended reassignments. We'll show why 'var' should never be used again.
We'll cover the following...
ES2015 introduces two new ways to declare variables. The keywords let and const. If you’re not familiar with these yet, here are the basics of these two keywords.
let
let is similar to var. It allows us to declare variables in our local scope. It’s used the same way, let x = 4;. The differences are that let is:
- not hoisted
- block-scoped
Not Hoisted
We’ve seen that variable declarations using var get hoisted to the top of their scope.
console.log(x); // -> undefinedvar x = 10;console.log(x); // -> 10
Variables declared with let, however, are not hoisted. Attempting to do the same with let will cause a reference error. x exists only at and after the line on which it was written.
console.log(x); // -> Uncaught ReferenceError: x is not definedlet x = 10;console.log(x);