What is the difference between var vs. let vs. const?

Many Javascript users don’t understand the difference between var, let, and const. I myself misuse them sometimes. Many articles give way too much detail that often just confuses newer developers. I’m going to explain this as simply as possible to help make the main differences stick with you. Hopefully this helps you to become 3 steps better at Javascript!

Var

Var allows you to change the variable whenever you want.

var num = 5;
console.log(num);  // 5

num = 3;
console.log(num); // 3  value can be changed

var num = 10;
console.log(num);  // 10  variable can be redeclared

Let

Let only works within it’s block {} scope. The variable’s value can change but it cannot be redeclared.

// Block Scope

let x = 10;
if (x == 10) {
    let x = 20;
    console.log(x); // 20  references x inside the block
}
console.log(x); // 10  reference at the beginning of the script

let num = 5;
console.log(num);  // 5

num = 3;
console.log(num); // 3  value can be changed

let num = 10;
console.log(num);  // error  variable canNOT be redeclared

Const

Const is a read only variable that will never change such as pi. If you try changing it, it will stop you.

const num = 5;
console.log(num); // 5

num = 3;
console.log(num); // error  value canNOT be changed

const num = 10;
console.log(num); // error  canNOT be redeclared

Hopefully this article gives the simple straightforward answer we were all looking for. Now you know the difference between var, let, and const and you are now 3 steps better at Javascript than when you started!

Leave a Reply