All have started with var…
var keyword that allows you to define a variable.
Here is an example of how we can use it:
Will the last line of code passe or fail?
Well, there is no problem with the code since the var keyword is not block-scoped. This means there is no scope for variables that are declared with var, whether they are declared inside or outside of a loop or a condition.
To resolve this problem, you need to declare you variable with let or const.
‘Let’ comes to solve the issue
let statement declares a block-scoped local variable, optionally initializing it to a value.
This time, the last line will fail since
i variable is declared with let inside if condition block, thus block scoped.
But, sometimes we need not only block-scoped variables but also immutable ones. Here comes the limitation of
When we need an immutable variable …
Const is the only way to declare a block-scoped immutable variable. This is generally a best practice when we are going to declare a variable that we won’t reset afterward. Immutable is generally a good approach that leads to fewer bugs and maintainable code.
Here is an example of
In this example, I show two cases. The first variable can’t be reset to null since it’s declared with the
The second case is declaring a
constobject. this time only the object reference is immutable that’s why we can’t set
objectbut we can set
varkeyword is not block scoped
- A local variable is not possible with
varkeyword should not be used while building a new typescript application.
letkeyword is block scoped
Constis for block-scoped variables and immutable variables
constobjects, only its reference is immutable.