Difference between var, let and const
Hi, this is a short read on the difference between var let and const in javascript.
Before now, var declarations ruled. There are issues associated with variables declared with var, though. But first, let's get to understand var more before we discuss those issues.
Var
Scope of var
The scope is global when a var variable is declared outside a function. This means that any variable that is declared with var outside a function block is available for use in the whole window.
var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.
var variables can be re-declared and updated
This means that we can change a valuable still using the var keywoed within the same scope and won't get an error.
If you have used a varuable in other parts of your code, you might be surprised at the output you might get. This will likely cause a lot of bugs in your code. This is why let and const are necessary.
Let
let is now preferred for variable declaration. It's no surprise as it comes as an improvement to var declarations. It also solves the problem with var that we just covered. Let's consider the main reason this is so. let can be updated but not re-declared. Just like var, a variable declared with let can be updated within its scope. Unlike var, a let variable cannot be re-declared within its scope. This fact makes let a better choice than var. When using let, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope. Also, since a variable cannot be declared more than once within a scope, then the problem discussed earlier that occurs with var does not happen.
Const
Variables declared with the const maintain constant values. const declarations share some similarities with let declarations. const cannot be updated or re-declared This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const, we can not redeclare it.
Conclusion
- var variables can be updated and re-declared within its scope;
- let variables can be updated but not re-declared;
- const variables can neither be updated nor re-declared.
Thanks for reading