In JavaScript we have several ways to declare our variables, but which one should you use?
As we know, depending on how we declare our variables, they’ll have different scopes.
If we declare them with var, they have a local scope. If we declare them with let or const, they have a block scope.
But let’s look at some other things to consider when deciding how to declare our variables.
How They Work
- With var we define a variable with local scope. It also allows us to use a behavior called hoisting without generating any errors.
- With let we define a variable with block scope. Variables declared this way will throw a reference error when we try to use hoisting.
- With const we define read-only variables (not to be confused with immutable). This means that when we assign a variable, its name will be bound to a pointer in memory that cannot be overwritten or reassigned.
const variable = 'esto';
variable = 'eso'; // TypeError: Assignment to constant variable
But if we create an object with const and try to change one of its properties:
const variable = { cosa: 'esto'};
variable.cosa = 'eso';
console.log(variable.cosa); //eso
This is why there’s confusion about the behavior of variables declared with const.
As I said before, it’s a read-only variable whose memory pointer can’t be reassigned, but things inside reference values can still be modified.
With primitive values like strings or numbers, they can’t be modified.
Readability
A fundamental aspect of our code is readability and how understandable it is when read by other developers or by ourselves in the future. That’s why I think let and const are a step forward in this regard.
A variable should be used to represent only one thing.
That’s why I’m in favor of const over let and var, since it lets us declare one thing per variable, making it clear that during the execution of our code it won’t be reassigned.
So, let should be used for variables inside loops or algorithm implementations like swap, where you need to exchange the values of two variables.
A powerful tool you can use to improve your code in this and other aspects is a linter. I especially recommend ESLint along with the Airbnb style guides for writing code.