JavaScript Variable Declarations: Exploring the Differences between Var, Let, and Const
Exploring the Scoping and Mutability Differences between var, let, and const and how to Avoid Common JavaScript Variable Declaration Mistakes
Variables in Javascript are used to give identity to storage locations with specific values. They are basically used to provide identity to values and store them in memory. There are three ways of declaring variables in Javascript which are var
, let
and const
. var
declaration was one of the first ways of declaring variables in Javascript until the intervention of ES6, then let
and const
declarations were introduced. In this article, we would be looking at each of these variable declaration methods with respect to their use and scopes.
var
The initial way to declare variables in Javascript before the intervention of ES6 was using var
, but there were some concerns associated with using var
to declare variables. Now, let's get into them.
Scope of var
The scope of a variable simply means the part of the code where that particular variable is available for use. var
declarations can be globally scoped and locally scoped also. It is global when it is declared outside of a function
while it is local when it is declared inside of a function
.
//Globally scoped
var name = "john";
console.log(name);
//Locally scoped
function aged(){
var age = "18"
console.log(age);
}
aged();
In the code above, name
is globally scoped and can be accessed from anywhere in the code, while age
is locally scoped and can only be accessed inside the function
.
function aged(){
var age = "18"
}
console.log("age") //ReferenceError: age is not defined
If we try to access the age
variable from outside of the function
, we get a reference error
stating that age
is not defined.
Hoisting of var
Hoisting is the process whereby a declared variable is moved to the top of its scope before it is executed. var
variables are initialized automatically on declaration with undefined.
console.log(day)
var day = "monday"
The code above outputs "undefined"
to the console because it interprets the code as below:
var day;
console.log(day) //undefined
day = "monday"
As we can see, the var
variable is hoisted and initialized with a value of undefined
.
Redeclaration of var variables
Variables declared with var
can be redeclared and can also be updated.
var name = "John"
var name = "David"
//the above variable was redeclared
var age = 14
age = 12
//the above variable was updated
both instances above are valid and would run perfectly.
Limitations of var
var name = "John"
var age = 18
function(vote){
if (age > 17){
name = "Mr john"
}
console.log(name) //output: Mr John
As we can see from the code snippet above, the variable name
was redeclared inside of the function
and it changed the overall output of the code. While this might not be a problem assuming we willingly wanted to redeclare the variable, it becomes a problem when we unintentionally assign a variable a name that has previously been assigned to another variable thereby resulting in an error
or undesired results in code. Therefore var
declarations are only advised when writing very short pieces of code.
let
The introduction of the let
declaration was a significant upgrade to the previous var
declaration as it addressed most of the flaws associated with var
. Now let's take a closer look at the let
declaration
Scope of let
let
declarations are block scoped which implies that they can only be accessed within the block of code in which they were created and not outside of it. Any attempt to access it from outside its block scope would result in an error
.
let weather = "rainy"
if(weather === "rainy"){
let advice = "please use an umbrella"
console.log(advice); //output: please use an umbrella
}
console.log(advice); //ReferenceError: advice is not defined
from the code snippet above, we can see that we are not able to access the advice
variable from outside its scope because as we said earlier, let
declarations are block scoped.
Hoisting of let
Just like var
, let
variables are hoisted to the top of their scope but are not initialized. Any attempt to use a let
declaration before its initialization will result in an error
console.log(name); //error:cannot access name variable before initialization
let name = "Precious"
Redeclaration of let
let
variables can be updated but can be redeclared, within its scope.
let name = "Precious"
name = "Aziken"
console.log(name); //output = Aziken
the above code would run smoothly as the name variable was only updated and not redeclared.
let name = "Precious"
let name = "Aziken"
console.log(name); //SyntaxError: name has already been declared
as we can see from the code snippet above, when we tried to redeclare the name
variable, we got an error
in the console telling us that the name
variable had already been declared previously. However, if the declaration were in different scopes, it would not result in an error because Javascript would run both as two separate instances. Take a look at the code snippet below:
let name = "Precious"
let water = "colorless"
if (water === "colorless"){
let name = "Aziken"
console.log(name); //output: Aziken
}
console.log(name);//output: Precious
This doesn't cause an error
because the declarations are present in different scopes, so javascript interpreted them as separate instances of code that are not related to each other. This is a significant upgrade to the previous var
declaration because you don't have to bother about whether you had used the declaration somewhere else in the code because the variable only exists within its scope.
const
The introduction of const
variable declaration in ES6 was also an upgrade to the previous version in which var
was used as reduced the chances of error
in the sense that any variable that had already been declared with const
cannot be changed within its scope.
Scope of const
Just like let
, const
declarations are blocked scoped and therefore cannot be accessed from outside of their scope.
Hoisting of const
Again, just like let
, const
declarations are hoisted to the top of their scope but are not initialized.
Redeclaration of const
As the name implies const
variables are constant meaning they don't change. They can neither be redeclared nor updated within its scope.
const name = "Precious"
name = "Aziken"
console.log(name); //error: assignment to constant variable
Trying to update the variable above with a new value results in an error
.
const name = "Precious"
const name = "Aziken"
console.log(name); //error: name has already been declared
Also, trying to redeclare a variable in the code snippet above results in an error
as const
declarations can also not be redeclared.
Now, let's take a recap of all we have learned so far:
var | let | const |
They are locally and globally scoped. | They are block scoped. | They are block scoped. |
Hoisted to the top of its scope and initialized with undefined. | Hoisted to the top of its scope, but is not initialized. | Hoisted to the top of its scope, but is not initialized. |
Can be declared without initialization. | Can be declared without initialization. | Must be initialized on its declaration. |
Can be updated or redeclared within its scope. | Can only be updated within its scope. | Can neither be redeclared nor updated. |
Conclusion
We have come to the end of this article and we should now be able to determine when to use let or const declaration when writing Javascript code. I would advise against using var
and just sticking to let
and const
alone to make the code written up to standard.