ES2015 Scope & Hoisting - let & const
Explore how ES2015 introduces let and const to provide block-scoped variables and prevent hoisting issues. Understand their differences from var, learn about reassignment restrictions for const, and how to choose between let and const for cleaner JavaScript code.
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.
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.