And when to use which?

Daan
Daan
Sep 6 · 4 min read

With the introduction of ES6, two important new JavaScript keywords were introduced as well: let and const. Before the introduction of ES6, the only way to declare a variable in JavaScript was by using var. But what is the difference between var, let, and const? And when do we use which type of scope?


Var

As you probably know, the old-fashioned way to declare a variable in JavaScript is by using the var keyword.

When you would log the name variable in your console, the output will obviously be Benjamin. The name variable has a global scope. It gets more interesting when we expand the script by adding a function.

What do you think that the output in the console will be? If you think that the output will be Benjamin, you’re wrong. This is because the name variable is defined within the setup function and has a function scope. This means that the variable can only be used within the setup function. The output of this example will be undefined.

It is possible to use variables with a global scope inside a function. This means that the age variable can be used inside the setup function. This will output Benjamin is 26 years old to the console.

You can only access variables that have the same scope or a higher scope. So, from inside a function, you can access the global scope. But, globally, you can’t access a variable that is created only in a function.

It is also good to know that a variable with global scope can be changed from within a function. In the example below, the age variable will be set to 35; thus 35 will be outputted in the console.

It gets more tricky when var gets used in a for loop or in an if statement. A for loop or an if statement won’t create their own variables. This means that the variable is more widely accessible than the loop or statement they’re created in. In the example below, the variable i has a global scope. This will lead to the output of 10 in the console.


Let

Let uses block scope and not lexical scope. This means that let does not care about global or local or whether you’re inside a function or not. Instead, let cares about the block you’re in. A block is basically anything with curly braces. This could be a function, but also a for loop or an if statement.

This means that in the example above, the variable i doesn’t get updated in the global scope; thus the output will be 5.

Let is useful when you want to have a variable scoped to its block. It is possible to access variables from a higher block, just like it is possible with var to access variables from a higher scope.


Const

Const works almost the same as let. However, the only difference is that once you’ve assigned a value to a const variable, you can’t reassign it to a new value. Just like the keyword implies.

The example above will give an error that tells you that you are trying to assign a new value to a const.

Const is great whenever you know that you have a variable that you won’t really change. And now you wonder, but why do we store a value in a variable if the value doesn’t change?

Part of that is true. On the other hand, you could use if for readability. You could choose to hard code some values in your code in multiple places, but using a const variable makes your code more maintainable. Whenever the hardcoded value changes, you only have to change the const variable, instead of going through the entire code looking for that hardcoded value.

In the example below, the username is a value that we get from the user input and will not change. A const variable makes the code much more readable.

const username = document.querySelect(‘input[name=”username”]’).value;

The same applies to the next example. Whenever you’re dealing with large objects, you could use a const to improve readability as well.

const books = api.data.sources[‘library’].books;

Using const can help make the intention behind your code clearer and more expressive. This is especially helpful when you work in a team. If someone sees a const in the code, that person knows that the value probably shouldn’t change.


The Exception: the Combination of const and objects

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

This means that the following is not possible since we try to reassign the const user.

But it is possible to change the properties of this object. This is because the value that a const holds is not immutable.


When to Use Which Type of Variable?

I think one of the only reasons that you should use var is when you work on a codebase that doesn’t support ES6.

Generally speaking, let is preferable over var because it reduces the scope. In most cases, you should be able to turn all var statements into let statements without any semantic changes.

Const is preferable over let. From a technical perspective, const is never a must. Every const could be replaced with a let variable, but using const can lead to cleaner code. Unless you need to mutate the value, use a const. This has all the benefits of let along with reducing the presence of uninitialized variables and making code more readable and expressive. If you aren’t sure if you will need to mutate a value, make it a const until you need to change it.

Better Programming

Advice for programmers.

Daan

Written by

Daan

Backend developer from The Netherlands. Crypto enthusiast.

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade