Skip to main content

Variables: let, const, var

Variables are named containers used to store data. In modern JavaScript (ES6+), there are three ways to declare variables.

1. let

Use let when you intend to reassign a value to the variable later. It is block-scoped, meaning it only exists within the curly braces {} it was defined in.

let score = 10;
score = 20; // Reassigning is totally fine!
console.log(score); // 20

if (true) {
let blockScope = "I only exist safely in here";
}
// console.log(blockScope); // Error! blockScope is not defined

2. const

Use const for values that should never be re-assigned. Like let, it is also block-scoped.

const PI = 3.14159;
// PI = 5; // Uncaught TypeError: Assignment to constant variable.

Pro Tip: Use const by default. Only switch to let if you explicitly know the value will change (like in a loop counter).

3. var (Legacy)

Before ES6 (2015), var was the only way to declare variables. It is function-scoped, which leads to unpredictable behavior in large programs due to "hoisting". Avoid using var in modern JavaScript.

var oldWay = "Avoid this!";