Difference between var, let, const in JavaScript
In JavaScript, one can declare a single variable in three different ways namely var
, let and const unlike any other programming language. This can prove a bit confusing to beginners as where to use a particular method.
Previously before the introduction of ES6, var
was the only way to write variables in JavaScript. But in ES6 two new ways namely, const
and let
were introduced to declare and write variables in a modern way. Now one might wonder, Is there any difference between these three techniques or Are they just the same? The answer is , YES they are different in nature as compared to each other. Firstly talking in terms of scope, var
is globally scoped while let
and const
can be defined as block-scoped variables.
For eg. see the code given below
In the above Image, You can see that the variables which are declared with var
keyword, will be accessed from anywhere in the code. Whereas, variables declared inside the For loop will not be accessed from outside as they are declared using let
and const
keyword.
Furthermore, Variables declared with var
keyword can be re-declared as well as updated, while variables with “let” keyword can only be updated they can not be re-declared. Last but not the least, the variables with const
keyword can neither be re-declared nor be updated. They all are hoisted at the top of their scope, while While var
and let
can be declared without being initialized, const
must be initialized during declaration
Thanks for Reading :)