One of the first and most important concepts you encounter in JavaScript is variables
JavaScript provides three main ways to declare variables:
- var,
- let, and
- const
While they may look similar, they behave very differently.
Variable
A variable is like a container that holds a value. You give it a name so you can reference or update that value later in your code.
Example:
let age = 16;
Here, age is assigned to a value of 16.
- var – The Old Way: var is the older method of declaring variables in JavaScript.
Key features of var:
- Function scoped
- Can be redeclared
- Can be updated
Example:
Redeclaration
var fruit = "orange"; // declearation
var fruit = "apple"; //redeclearation
console.log(fruit); // apple
Making update
var fruit = "orange";
fruit = "apple"; // update
console.log(fruit); // apple
Redeclaring a variable may overwrite values unexpectedly, making bugs harder to track.
- let – This was introduced to fix many of the problems caused by var.
Key features of let:
- Block scoped can be updated
- redeclared.
Example:
let age = 16; // declaration
age = 17; // updating (allowed)
console.log(age); // 17
// Redeclaring in the same scope will cause an error:
let age = 16;
if (true) {
let age = 18; // allowed, block-scoped
}
- const – const is used for Fixed Values. const is used for values that should never change.
Key features of const:
- Block scoped,
- Cannot be updated and
- Cannot be redeclared.
- It Must be initialized immediately
Example:
const country = "Nigeria";
Using the correct variable type helps:
- Prevent bugs
- Make your code more readable
- Improve maintainability
Best Practices for Declaring Variables in JavaScript:
- Use const by default — for values that should not change.
- Use let only when you need to update or reassign a variable.
- Avoid var in modern JavaScript to prevent unexpected redeclarations and scope issues.
Top comments (0)