In this article, I will cover the differences between var, let and const. Before ES6 you could only use var to define the variables. So, what are three different ways to define variables and what's the difference between in these?
Before we understand the differences first we need to understand the scope. So, basically, there are two kinds of scope such as functional-scope and block-scope.
Scope describes the availability of variables created by code blocks , functions etc.
Function scope is any variable that is declared inside the function that can be accessed anywhere within that same function but can't access outside. Block scope means declaring a variable in curly braces and is used for control flow such as if-else-statement, while and for loop etc.
Var :
The variable var is function scope because their visibility is within the function. If you try to use it outside the scope of function then you will get an error which is shown in the below example.
Var can be updated and redeclared as shown in below example:
Let & const :
The code between curly braces is known as a block of code or block -scope. The variable let and const are block-scope.
Here the visibility of b & c is limited because they are declared inside the if-statement block whereas the visibility of a isn't limited.
let is the improved version of var declarations. Also, let can't be redeclared and can be updated. Check out the below example to understand the behavior of let.
const can't be updated and redeclared.
If we use objects or arrays then we can update properties or values inside of that object or array. let's see the below example for better understanding:
Its useful to use const instead of let because its prevent the overwriting variables.
So, hope this article will help you understanding the differences between var, let and const.