How to use var, const and let

The new keywords const and let come to replace var keyword. They affect directly to the variable’s scope and its modificable properties.

When we use const we are declaring an inmutable variable, but keep in mind that this only affect to primitive values such string, integer … if we declare an object, we cannot reassign its type but we can modify its inner properties.

1
2
3
const PI = 3.141593;
console.log(PI); // 3.141593
PI = 2.0 // TypeError: Assignment to constant variable.

With the keyword let we are declaring a modificable variable with a close scope. Its scope is defined but its parent scope. So if we declare a let variable inside a function, it’s local to that function.

1
2
3
4
5
for(let i=0; i<10; i++){

}

console.log(i); // ReferenceError: i is not defined

Which should I use?

Always try to use const when declare a variable, only use let if your variable will be modified like an index variable in a loop for example. If you have a mistake using const, it will be throwed in the 98% of cases, so don’t worry about it.

References