Mastering Variable Declaration in JavaScript: When to Use var
, let
, or const
Just as in everyday life, where we use names and containers to organise our belongings, JavaScript employs variables to store and manipulate important information. This post will go through the three variable types: var, let, and const.
Think of variables as special containers that hold important data. However, not all containers are the same! Each keyword — var, let, and const — has unique abilities and characteristics.
Before diving in, if you have yet to read my post on Javascript scopes or need to know what scope means, I recommend you read it before continuing.
What is var?
Although var is an older way of declaring variables, it is still important to understand its differences compared to the newer let
keyword.
Variables declared with var
have either function scope or global scope. This means they are visible throughout the entire function or script.
function castSpell() {
var wand = "Elder Wand";
console.log(wand); // Output: Elder Wand
}
castSpell();
console.log(wand); // Output: Error - wand is not defined
In the above example, the variable wand
is declared with var
inside castSpell()
. It is accessible anywhere within that function but not outside of it. If we try to access wand
outside the function, we will get an error because var
variables are limited to their enclosing function or script.
One exciting thing about var
is that we can redeclare it multiple times without any error. However, redeclaring a variable using var
doesn’t change its value or affect its previous assignments.
var broomstick = "Nimbus 2000";
var broomstick = "Firebolt"; // Redefinition of 'broomstick'
console.log(broomstick); // Output: Firebolt
In the above example, we initially declare the variable broomstick
with a value of Nimbus 2000
. Then, we redeclare it with a value of Firebolt
using var
. The variable broomstick
retains its last assigned value, which is Firebolt
.
With var
, variable declarations are processed when the function starts or when the script starts for global variables. This means that var
variables are defined from the beginning of the function, regardless of where the declaration appears in the code.
console.log(potion); // Output: undefined
var potion = "Polyjuice Potion";
console.log(potion); // Output: Polyjuice Potion
In the above example, even though the variable potion
is accessed before its declaration, it doesn’t throw an error. Instead, it prints undefined
because the variable declaration is hoisted to the top of the function.
While var is still used in some older scripts, using the newer let keyword is generally recommended to avoid confusion and potential errors.
What is let?
To declare variables in a clear and reliable way, we have the let
keyword. Unlike its older counterpart, var
, let
offers improved clarity and helps avoid confusion and errors.
The let
keyword brings clarity to variable declarations, making our code easier to understand and maintain.
let broomstick = "Nimbus 2000";
console.log(broomstick); // Output: Nimbus 2000
In this example, we declare the variable broomstick
using let
and assign it the value Nimbus 2000
. The use of let
makes it explicit that we are creating a new variable, improving the readability and clarity of our code.
Variables declared with let
have a block-level scope, meaning they are only accessible within the block of code where they are defined.
{
let spell = "Expecto Patronum";
console.log(spell); // Output: Expecto Patronum
}
console.log(spell); // Output: Error - spell is not defined
In this example, the variable spell
is declared using let
within a block of code. It can be accessed and used within that block, but once we step outside the block, it becomes inaccessible and attempting to access it will result in an error.
Unlike var
variables declared with let
are not hoisted. They must be declared before they are used to avoid unexpected behaviours or errors.
console.log(potion); // Output: ReferenceError - potion is not defined
let potion = "Polyjuice Potion";
console.log(potion); // Output: Polyjuice Potion
In this example, trying to access the variable potion
before its declaration using let
results in an error. However, once we declare and assign a value to potion
we can access it without any issues.
The let
keyword is the recommended way to declare variables in JavaScript. By using let
we improve the clarity and readability of our code. We also benefit from block-level scoping, which ensures that variables are only accessible within their respective blocks. Furthermore, the absence of hoisting surprises helps us write more reliable and error-free code.
What is const?
To create values that cannot be changed, we have a special keyword called const
. Unlike let
and var
, const
allows us to declare variables that remain constant throughout the program.
The const
keyword helps us create variables with values that cannot be changed or reassigned.
const spell = "Expelliarmus";
console.log(spell); // Output: Expelliarmus
In this example, we declare the variable spell
using const
and assign it the value Expelliarmus
. Once the value is assigned, it remains constant and cannot be modified.
Variables declared with const
act as reliable constants, providing strong protection to their values. Once a value is assigned to a const
variable, it cannot be changed.
const age = 12;
age = 15; // Error: Assignment to constant variable
console.log(age); // Output: 12
In this example, we attempt to change the value of the age
variable declared with const
. However, we encounter an error indicating that we cannot assign a new value to a const
variable. The original value remains unchanged.
When using const
, it is necessary to initialise the variable with a value during declaration. const
variables cannot be left undefined.
const potion; // Error: Missing initializer in const declaration
In this example, we try to declare a const
variable named potion
without initialising it with a value. This results in an error, reminding us that const
variables must have an initial value.
The const
keyword in JavaScript allows us to create variables with constant and unchangeable values. By using const
, we ensure the immutability of values, providing stability to our code.
In conclusion, mastering variable declaration in JavaScript involves understanding the differences between the var, let, and const keywords.
JavaScript developers can write more reliable, error-free, and maintainable code by choosing the appropriate keyword for variable declaration, whether var, let, or const. Understanding each keyword's unique abilities and characteristics allows for effectively organising and manipulating essential data in JavaScript programs.