Back to Blog List

When Should I Use const vs let in JavaScript?

You should use const when the value of your JavaScript variable is not going to change. If the value of the variable will be re-assigned, then use let.

Oftentimes we run into a very popular question: when to use const vs let in my code. In many code languages, the word const represents a variable whose value cannot be changed once it's been initialized or assigned. This means that if you expect your variable to change, you should use let, so that you are able to re-assign a new value to the variable.

Immutable Objects

You should be aware that if using const, although the value itself cannot be changed, you can still change the value of any child items within a const variable. So for example, let’s say you have the following user object:

const user = {
  name: 'Jorge Felico',
  age: 31
}

Although you can’t change the entire value of the user variable, you can still update the values within it, so the following code would be valid.

user.name = 'My new value'
user.age = 32;
2024 | Coded with ❤️️ by Jorge Felico