var vs let vs const in JavaScript

What’s the difference between var, let, and const in JavaScript
First of all, they are all used to create variables in JavaScript.
Second, var sucks, that’s why let and const are created.
var is function-scoped, while let and const are block-scoped.
Here we wrap the variables with an if block, creating a block scope, and try to console log it from the global scope.
if (true) {
var name = "denji";
let name2 = "power";
const name3 = "aki";
}
console.log(name); //denji
console.log(name2); // ReferenceError
console.log(name3); // ReferenceError
You would expect them to throw an error. Which is true for let and const.
But for var?
It works just fine and ignores the block scope completely.
And it gets worse. You can't redeclare let and const variables in the same scope.
let foo = 1;
let foo = 2; //error
But, it's possible with var. That means you can accidentally overwrite variables without even realizing it.
var foo = 1;
var foo = 2; //ok
The final difference is that you can access a var variable before it’s created:
console.log(foo); // undefined
var foo = 'foo';
console.log(baz); // ReferenceError: Cannot access 'baz' before initialization
let baz = 'baz';
console.log(bar); // ReferenceError: Cannot access 'baz' before initialization
const bar = 'bar';
But you can't do that with let and const.
So var sucks, got it.
What about let and const? How are they different?
You can reassign a let variable after it’s declared, but you can’t do it with a const variable.
let name = "power";
name = "zerotwo"; //ok
const name2 = "power";
name2 = "zerotwo"; //error
So use a let variable when you need to change the value of the variable; otherwise, always use const.
Get the written notes delivered to your email inbox to learn something new about javascript one at a time.