Why is const used instead of var/let?

Why is const used instead of var/let?
0

#1

In the ES6 challenges const is used instead of var or let. It seems to me in these examples it doesn’t matter, so why the change to const?

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-the-rest-operator-with-function-parameters


#2

Generally accepted best practise is use const everywhere, unless you need to reassign the value of a variable, in which case use let. var has problems, which const and let exist to solve, so its generally pointless using it.

Const prevents accidental mutation, it throws errors a lot more, avoids accidents.


#3

**const** is a signal that the identifier won’t be reassigned.

**let**, is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it’s defined in, which is not always the entire containing function.

**var** is now the weakest signal available when you define a variable in JavaScript. The variable may or may not be reassigned, and the variable may or may not be used for an entire function, or just for the purpose of a block or loop.


#4

But be careful with const.
It only prevents new assignment, not mutation.
This is important for non-primitive values like arrays and objects.

const fruits = ["apple", "banana"]; // apple, banana
fruits.push("orange");
console.log(fruits); // => apple, banana, orange

The assignment to a location in memory can’t change,
but the content can.


#5

Excellent replies, thank you!


#6

const does not make the variable immutable, as @miky86coding pointed out. What it does it prevent rebinding.

The reason that you do this is to make your code easier to reason about. You know what to expect when there is a const variable, where if it were set with let it could be anything.

var is even worse. When you use var, you place the variable into the global namespace. That means your variable could be mutated both any time and any where in the code.

Imagine if you declared a variable with var and then when debugging later, you find a case where it is null and it shouldn’t be. You mau have to scour your entire codebase looking for the problem.

Code with less variance and unpredictability is better code. Using tools like const allows you to remove some variance and make your code more reliable and easier to read.