The Difference Between var, let and const in JavaScript: Part 2

Back to the basics with variables and scope

It’s just a beautiful photo and has nothing to do with JavaScript, by Badder Manaouch on Unsplash

The Differences Between let and var

An example of trying to redeclare a let variable:// In editor:<script>
let points = 50;
let points = 60;
</script>
// In the console I get an error:
Uncaught SyntaxError: Identifier 'points' has already been declared
let points = 50;
points = 60;
// In console:
points
// Returns:
60

The Scope of let

let points = 50;
let winner = false;
if(points > 40) {
let winner = true;
}
// If I call:
winner
// It returns the first value:
false
// This 'let' is scoped to the window (globally):
let winner = false;
if(points > 40) {
// This 'let' is scoped to the block (between the curly brackets):
let winner = true;
}
let points = 50;
var winner = false;
if(points > 40) {
var winner = true;
}
// If I call:
winner
// It now returns:
true

The Differences Between let and const

// If I define the const variable:
const key = 'xyz123';
// Then try to redeclare it:
key = 'xyz1234'
// I get the following error:
Uncaught TypeError: Assignment to constant variable.
// Creating my person object:
const person = {
name: 'Joseph',
age: 33
}
// Calling person in the console:
person
// It returns:
{name: "Joseph", age: 33}
// If I then redeclare the age attribute:
person.age = 34
// When I call it:
person
// It returns:
{name: "Joseph", age: 34}
const joseph = Object.freeze(person);
// If I call:
person
// It returns:
{name: "Joseph", age: 33}
// However, if the object has been 'frozen' and I try to change the age attribute:
person.age = 34
// It will immediately return:
34
// But then when I call it:
person.age
// It returns the original age:
33

The advantages of using let vs. var in a for loop

// Running a for loop with var:
for(var i = 0; i < 10; i++){
console.log(i);
}
// Returns 0 through 9 in the console, but if I call:
i
// It returns:
10
// Do something one second after the loop runs:
for(var i = 0; i < 10; i++) {
console.log(i);
setTimeout(function() {
console.log('The number is ' + i);
}, 1000);
}
// If we then call i in the console it returns:
10
for(let i = 0; i < 10; i++) {
console.log(i);
setTimeout(function() {
console.log('The number is ' + i);
}, 1000);
}
// This returns 0 through 9 in the console, then after one second logs:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

Coding, creativity, music, and books. Pianist & composer — @vontmer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store