What is a Variable?
A variable in its simplest of terms can be said to be a container in which a value is stored in and can be reused in the code later on. As you can see in the code below the variable greeting now holds the value hello user which can be reused later on in the code if needed.
- Declaring or Re-declaring
- Assignment or Reassignment
This is where var can be tricky, and it was one of the reasons the other keywords where created. The problem with var is that it is function scoped and if there is not a function then var will be globally scoped. While let and const are block-scoped. The following code snippets should help you understand.
In this if statement, you must have noticed the variable was declared in the if block, but yet the console.log could still find it why? In this case, there was not a function so the var keyword made variable globally scoped i.e outside the if block
The let and const keyword behaves the same when dealing in scope context. As in the code above, the variable was declared in the if block, so when console.log looked for it, it could not found, hence the Reference error. But if console.log was called inside the if block, it would be seen and logged to the console.
This concept doesn’t only work in if statement but also in for loop
This is a good example of the keyword var scope issue. After the loop had finished variable i still added 1 to its previous value and because var keyword is function scoped the console.log referenced the variable i on the function level not block-level like the let keyword.
It is best to use let or const so as to prevent your code from misbehaving due to the scope issue of var.
Declaring or Re-declaring
It is possible for a developer to re-declare a variable by mistake. This could happen due to either the developer does not know that the variable has been declared. This is also var’s shortcomings, let look at the codes snippet below.
The code above declared a variable and re-declared it thereby changing the value of the variable to the new value.
This is also where let and const have similar behaviour they cannot be re-declared after they been declared. This free you from having to know every variable name you have created to avoid it from being overwritten and alsoe keeps in check.
Assignment or Reassignment
Though var and let behave the same when you want to reassign a variable to value. On the other hand, const differs from the rest in this regard.
FYI: When declaring a variable it is best practice to use either the let or const keyword to avoid any issue with your code most times use const, you can use let if you intend to change the value of the variable later on.