Let:
- Variables that can change (be reassigned).
- Take in account block scope instead of function scope (e.g. issue var for or if).
Const:
- Variables that cannot be reassigned ()
More info: https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75
- Let's open codepen and click on create >> new Pen
-
On Settings let's untick the option Behavior >> Auto-updatingPreview (we want to have a run button).
-
Let's add the following code snippet:
function myFunction() {
var myVar = 2;
if(myVar < 3) {
var myVar = 3;
console.log(`** Inside if statement: ${myVar}`);
}
console.log(`** Outside if statement: ${myVar}`);
}
myFunction();
- Check that we get in both console logs the value '3', this is caused because var works at function scope.
** Inside if statement: 3
** Outside if statement: 3
- Let's replace this "var" based code with a "let" based code.
function myFunction() {
- var myVar = 2;
+ let myVar = 2;
if(myVar < 3) {
- var myVar = 3;
+ let myVar = 3;
console.log(`** Inside if statement: ${myVar}`);
}
console.log(`** Outside if statement: ${myVar}`);
}
myFunction();
- Now we get the expected block scope behavior.
"** Inside if statement: 3"
"** Outside if statement: 2"
- Let's start with another simple sample, using let and reasigning:
function myFunction() {
let myVar = 2;
myVar = 3;
console.log(`** Outside if statement: ${myVar}`);
}
myFunction();
-
So far so good, it works.
-
What would happen if we use const ?
function myFunction() {
- let myVar = 2;
+ const myVar = 2;
myVar = 3;
console.log(`** Outside if statement: ${myVar}`);
}
myFunction();
- Now if we open the console (browsre console, F12) we get the following error:
Uncaught TypeError: Assignment to constant variable.
at myFunction (pen.js:10:9)
at pen.js:15:1
That's because using const, it doesn't allow to reassign the variable.
Important 'const' is not about immutability, is about immutable binding: https://mathiasbynens.be/notes/es6-const
Two nice points to extend:
let
.const list = []; list.push("a");
is the best example of immutable binding but mutable instance.