Introduction
In JavaScript, there are three ways of declaring variables. You can use any of the following keywords for variable declaration - var
, let
, and const
.
However they do not behave in the same way. What is the difference? And how do you know which one to use and when?
In this article, you'll learn how each of these keywords works and when to use them. Okay, let's get started.
Var
Before ES6 was introduced in 2015, var
was the only keyword available for declaring variables. However, var
had some limitations (which you will learn about in this article).
Scope of var
Variables declared with var
are functionally scoped or globally scoped if it is declared outside of a function.
This means if a variable within a function is declared with var
, that variable is available anywhere within the function. And if it is declared outside of a function, then it is available globally.
Let's consider some examples.
var globalVariable = "Some Text"
function myFunction() {
var funcVariable = "Hello World"
}
console.log(funcVariable) // Error: funcVariable is not defined
From the example, globalVariable
would be available within the entire program.
However, funcVariable
is not as it is functionally scoped. Thus, if we try accessing funcVariable
from outside of the function where it is declared, JavaScript throws an error funcVariable is not defined
.
Var
- Redeclaration (✅), Reassignment (✅)
Variables declared with var
can be redeclared. They can also be reassigned new values.
var firstVar = "Some Text";
var secondVar = "Frontend"
console.log(firstVar) // Prints Some Text
console.log(secondVar) // Prints Frontend
var firstVar = "Different Text"
secondVar = "Backend"
console.log(firstVar) // Prints Different Text
console.log(secondVar) // Prints Frontend
In this example. The firstVar
was redeclared and a new value was assigned to the secondVar
. JavaScript threw no error because, with the var
keyword, such redeclaration and reassignment are allowed.
This is a major weakness of var
. It can lead to redeclaring already existing variables. And this can result in bugs that can be a pain to fix.
This was a significant reason why let
and const
keywords were introduced in ES6.
Let
The let
keyword has both some differences and similarities with var
. Let's now take a closer look at let
.
Scope of let
Variables declared with let
are block scoped. This means they are only available within the block in which they are defined. A block
is a snippet of code surrounded by curly braces {}
. Common examples are if statements
and for loops
.
Let's consider some examples of let
variables to understand better.
let firstName = "Maria"
if (firstName === "Maria") {
let lastName = "Gracia"
console.log(firstName, lastName) // Prints Maria Gracia
}
console.log(firstName, lastName) // Error: lastName is not defined
The first console.log within the if statement prints Maria Gracia
. Both the firstName
and lastName
variables are available.
The second console.log throws an error lastName is not defined
. This is because lastName
is being referenced outside of the scoped where is was declared.
Let
- Redeclaration (❌), Reassignment (✅)
A variable declared with let
cannot be redeclared but a new value can be assigned to it. Let's see an example to understand what this means.
// let variable cannot be redeclared
let result = "positive"
let result = "negative"
console.log(result) // Error: Identifier 'result' has already been declared
In this example, we can see that redeclaring an already present variable result
with let
will leads to the following error Identifier 'result' has already been declared
.
This is one of the ways in which let
differs from var
.
A let
variable cannot be redeclared but the value of that variable can be changed or updated. See the example below.
// let variable can be assigned a new value
let greeting = "Hello!"
greeting = "Welcome"
console.log(greeting) // Prints Welcome
The greeting variable is initialized with the value "Hello!". And we were able to update the value to "Welcome".
Const
The const
keyword is useful when it comes to declaring constant variables. These are variables whose value do not change.
For example, if you have a userID variable and you want the value of that variable to remain constant throughout your application, then, ideally, you should declare it with const
.
Scope of const
.
Just like let
, variables declared with const
are also block scope and cannot be accessed outside of the block where they were declared.
Const
- Redeclaration (❌), Reassignment (❌)
All const
variables are constants. They can neither be redeclared nor reassigned. Their values cannot be changed. Any attempt to reassign a new value to a const
variable will throw an error.
// Redeclaring const will throw an error
const dateOfBirth = "01-Jan-2022"
const dateOfBirth = "02-Jan-2022" // Error: Identifier 'dateOfBirth' has already been declared.
// Assigning a new value to const will throw an error
const PASSWORD = "123"
PASSWORD = "abc" // Error: Assignment to constant variable.
// The values of the properties of objects declared
// with const can be updated. See example below.
const person = { name: "Augustus", age: 23 }
console.log(person.name) // Prints Augustus
person.name = "Dominic"
console.log(person.name) // Prints Dominic
NOTE: Only the values of the properties can be updated. The object itself CANNOT be updated. (See example below).
const person = { name: "Augustus", age: 23 }
person = { country "Ghana", code: 233}
// Error: Assignment to constant variable.
Quick Recap.
var
Functionally or globally scoped. Can be redeclared. Can be reassigned.
let
Block scoped. Cannot be redeclared. Can be reassigned.
const
Block scoped. Cannot be redeclared. Cannot be reassigned.
Conclusion
It is advisable almost always to stick to let
and const
. Use let
for a variable that you expect to change in your application. For those variables that are expected to remain constant, use const
.
This can save time and effort spent in fixing bugs that can could have easily been avoided.
Now you know the differences and similarities between var
, let
, and const
. And more importantly, when to use them. Cheers!
Thanks for reading.
Let's connect on LinkedIn | Twitter