Understanding the difference between let, var char and const in JavaScript
Let us begin with understanding var . It is the oldest way to declare variables in JavaScript
Scope of var:
var variables are globally as well as function/locally scoped .It means if we define it outside the function then they are globally scoped if they are defined inside the function they are locally scoped and can’t be used outside the function as we can see it in example below.
Problems in var:
Now one of the major problem in is that they can be re declared means if we have already declared a variable with some particular name then we can re declare it with same name and differently and it’s value will be updated. If this is done knowingly but it becomes a problem when you too many lines of code and you don’t remember each variable you have defined.
So that’s where we can use let or const to help us out in this situation
Scope of let:
Let variables are block scoped , means that they can be used within the curly brackets {} they are defined .Now better part in Let than var is that we can update the let variables but we cannot re declare them.
Now but one thing is if we define a new variable x with let keyword inside a function then it will not throw any error since they are defined in different scopes.
Now let’s look at const.
Scope of const:
Similar to let const are also block scoped and can be accessed only within the curly brackets they have been defined
So the difference between let and const is we can neither re declare or update the value of const variable
Also if we define any object with const keyword we can’t re declare it either for example:
However to update the values for object x we can do that like this
So in a nutshell these are the major differences
var
declarations are globally scoped or function scoped whilelet
andconst
are block scoped.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.
If you have any question comment it.
Thank you