JavaScript Concept
Source: Dev.to
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.
var – The Old Way
Key features of var
- Function scoped
- Can be redeclared
- Can be updated
Example
// Declaration
var age = 16;
// Updating
age = 18;
// Redeclaring (may overwrite values unexpectedly)
var age = 20; // <-- allowed, but can lead to bugs
let
Introduced to fix many of the problems caused by var.
Key features of let
- Block scoped
- Can be updated
- Cannot be redeclared in the same scope
Example
let score = 10;
// Updating
score = 15;
// Redeclaring in the same block causes an error
// let score = 20; // Uncaught SyntaxError: Identifier 'score' has already been declared
const
Used for fixed values that should never change.
Key features of const
- Block scoped
- Cannot be updated
- Cannot be redeclared
- Must be initialized immediately
Example
const country = "Nigeria";
// Attempting to reassign throws an error
// country = "Ghana"; // Uncaught TypeError: Assignment to constant variable.
Benefits of Using the Correct Variable Type
- Prevent bugs caused by accidental reassignments or redeclarations
- Make your code more readable and intention‑revealing
- Improve maintainability by clearly signaling mutability
Best Practice
- Use
constby default – when a value should not change. - Use
letwhen you need to update a value. - Avoid
varin modern JavaScript unless you have a specific reason for its function‑scoped behavior.