let and const

Introduction
In this subunit, we'll dive deep into the let and const, new ES2015 keywords used to declare variables. They both introduce a new kind of scope into JavaScript, and these keywords set rules on whether we can reassign or redeclare variables. This subunit will teach you all you need to know about what makes these keywords so powerful and what sets them apart.
Reviewing var
var
We use the var keyword to declare variables
When defined in a function, the var keyword scopes a variable to that function
var will hoist to the top of the scope it is defined in
You can redeclare and reassign values with var
let
The let keyword creates a block-scoped variable: a variable that only exists inside a code block.
What Is A Code Block
Essentially any pair of curly braces (outside of object syntax).
Where Are Code Blocks Commonly Used
You’ll mostly use code blocks in for loops and if statements.
An Example
More About let
It can be reassigned but not redeclared (unlike var).
const
The const keyword prevents a variable from ever being reassigned or redeclared.
const is also block-scoped, like let.
Comparison of Variable Declaration Keywords
Keyword | Can Reassign | Can Redeclare | Can Mutate | Scope Rules |
---|---|---|---|---|
var | yes | yes | yes | function scope |
let | yes | no | yes | block scope |
const | no | no | yes | block scope |
What about var
There's really no need to use it
Just be careful of block scoping with let