10 Tweets 1 reads Apr 18, 2023
It is very important to understand the difference between let, const, and var in ES6.
Take a look:
1. let
β€” β€œlet” is used to declare a block-scoped variable. It means that the variable declared with β€œlet” can only be accessed within the block in which it was declared.
In this example, β€œx” is declared twice, first in the β€œtest()” function and then within the β€œif” block. The two variables are completely separate from each other because they have different scopes. This is because β€œlet” is block-scoped.
2. const
β€” β€œconst” is also used to declare a block-scoped variable, but with the difference that its value cannot be reassigned once it is initialized.
In this example, we try to reassign the value of β€œx” to β€œ3”, which will result in an error because β€œconst” variables cannot be reassigned.
3. var
β€” β€œvar” is used to declare a variable with function-level scoping. It means that the variable declared with β€œvar” can be accessed within the function in which it was declared, or even outside the function if it is declared globally.
In this example, β€œx” is declared twice, first in the β€œtest()” function and then within the β€œif” block.
The second declaration of β€œx” using β€œvar” is not creating a new variable with a new scope, bt rather modifying the original variable, which is accessible outside the β€œif” block.
Recommendation πŸ’‘
Overall, my recommendation to use β€œlet” and β€œconst” instead of β€œvar”, especially in modern JavaScript, because β€œlet” and β€œconst” provide block-scoping, which is more predictable and less error-prone.
You can get my free JavaScript e-book that has 100+ free resources.
πŸ”— haiderkh1.gumroad.com
That's a wrap!
If you enjoyed this thread:
1. Follow me @slow_developer for more of these
2. RT the tweet below to share this thread with your audience

Loading suggestions...