Const and Let is a new feature introduced in ES6. This article will explain the difference and usage of const and let
Definition
First of all, let’s take a look at the definition in MDN
- Const : block-scoped, much like variables declared using the
let
keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared. - Let: statement declares a block-scoped local variable, optionally initializing it to a value.
By reading the definition, we can see that the main difference is on reassignment. In the next section, I will get into more detail on the feature comparison and provide an example to show you the error message you will get when use it in the wrong way.
Feature Comparison
- Reassignment: You can only reassign value with the variable declared by let. If you try to reassign a value declared by const, you will get below TypeError
- Redeclared: As both const and let are block scope varible, you awill get syntx error if you are trying to redeclare it in the same block({})
- Block-scoped: Follow up on the previous point, if you try to declare it in the global level first and redeclare it in block level, you will not get any error.
- Update call by reference property: This is one of the feature that people get confused easily. The definition of reassignment we are referring here is actually reassignment on reference. .Because both array and Object are calll be reference. This explain why you are able to push new value to an array that been declared with const and change the property of object that declare with const
Array
Object
NOTE: You are not able to reassign it in below 2 ways, because it means that you are changing the memory address
To make it easy to compare, I made below table so I can easily reference it whenever I am not sure which one to use
Usage
Still not sure how to use it properly? I have listed out some of the common scenarios we face which will give you an idea how to use it properly
- use Const when you declare a variable that doesn’t want anyone else to change it
This is a good practice to follow when you are working on a project. By declaring it as a const, other engineers will know that this is a static varible that shouldn't be changed
- const functionName = () =>{}
When you are declaring an arrow function, we normally see people declare it with const
- use let in for loop
When declaring a for loop, use let as your i value will change.