The ES6 Javascript standards introduced the let and const method of declaring variables. These are to add more features to the variables overcoming some of the short comings of the var based variable declaration. We will be using ES6 let and const variables to see and understand the difference between these types of variable declarations.
Understanding these differences are easy and pretty straight forward but only thing is that we will be working with the sample project that is created using the create-react-app. So if you do not have the React project created using create-react-app, then follow our article Create New Project using create-react-app.
Now that we have the boiler plate project setup ready, you can start writing the code in the index.js file:
Problem with var based variables:
The major problem with the old var based variable declaration is that with the var based variables you can not only reassign values for the variable but also redefine the variable. Consider the following example:
var myName = "Sam"; myName = "Tom"; //re-assigns value var myName = "Spark"; //redefines the myName variable
In the above example, you can notice that the variable “myName” is being reassingned. It is also being redefined next which is the major cause of concern. Image a bigger enterprise level application and if any one of the variable name is being redefined by some other developer’s code, identifying & debugging would definitely be a pain point. This can be overcome by using the let variables.
Using let variables:
With the let based variables declaration, you can only reassign but not redefine the variable. Consider the following code example:
let myName = "Sam"; myName = "Tom"; //can re-assign value let myName = "Spark"; //Cannot redefine the myName variable - will throw error
Here in this code upon trying to redefine the “myName” variable, it will throw compilation error that the “myName” variable has already been declared.
Using const variables:
With the const variables, you cannot reassign and cannot re-declare the variables. Consider the following examples with first one showing the error being displayed when trying to re-assign the value:
const myNameConst = "Sam"; myNameConst = "Tom"; //Cannot re-assign value - will throw error
The following example shows the error being displayed when trying to redefine the variable declared as a const:
const myNameConst = "Sam"; const myNameConst = "Spark"; //Cannot redefine the myName variable - will throw error