Difference between Var, Let, and Const, a simple definition
Javascript has been evolving, and it has had a long journey. ES6 is the latest javascript standard that is being adopted by the majority of developers in the world, but still, certain concepts are not evident among them.
One such addition in the ES6 is the new variable declarators, let and const. This article will be looking at how these new declarators differ from the older var keyword and each other.
We will also be discussing them concerning their scope and use.
Let us dive into it now.
Redeclaring and updating
All three of the keywords have their own rules when it comes to redeclaring and updating the variables.
With var, you can easily redeclare and update the variable.
Whereas with let, you can change the variable but declaring one with the same name throws an error.
Lastly, once a const variable has been declared and assigned a value, you cannot change it, nor can you redeclare it.
Scope
The scope of a variable tells us where Var, Let, or Const can use it.
Var has a different scope as compared to let and const. Var is globally scoped and locally scoped. If var is created outside of a function, it can be accessed anywhere. But if it is declared inside the function, it cannot be accessed outside of it.
Let, and const, both are blocked scope, i.e., their scope lies within the curly braces. It can be a function, a switch statement, an if-else, or anything inside the braces.
Hoisting
When it comes to hosting, all declaration keywords are moved to the top of their scope before any execution happens. But the main difference is that var is assigned undefined value whereas, let, and const throw a reference error if used before the declaration.
Conclusion
With these differences, you can advise using the new declarations from the ES6 to save you from many weird issues. Knowing the use of each declaration can make your code logically strong.
That is all, happy coding!