Declaring Variables: let, const, and var
In JavaScript, variables are like labeled containers where you store values—like numbers, text, or even complex data. You’ll use variables in almost every program you write. To create a variable, JavaScript gives you three main options: let
, const
, and var
. Each works a bit differently, and knowing when to use each one is an important step in becoming a confident JavaScript developer.
let vs const vs var
Let’s start with the modern way: let
and const
. These two were introduced in newer versions of JavaScript and are now recommended over var
, which is older and has some strange behavior.
let
is used when you need to create a variable that can change later.
let age = 20;
console.log(age); // Output: 20
age = 21; // This is fine
console.log(age); // Output: 21
const
is for values that should not change after being set. It stands for “constant.”
const birthYear = 2000;
console.log(birthYear);
birthYear = 2001; // ❌ This will cause an error
- If you’re sure the value won’t change, use
const
. - If the value might change, use
let
.
var
is the old way of declaring variables. It still works, but it behaves differently and can cause unexpected problems, especially in larger programs. It’s best to avoid var
unless you’re working with older code.
var name = 'Alex'; // Still works, but not recommended
console.log(name); // Output: Alex
Naming rules and best practices
Variable names should be clear and easy to understand. JavaScript has a few rules and suggestions:
- Variable names can contain letters, numbers, dollar signs (
$
), and underscores (_
)
let userName = 'Sara';
console.log(userName); // Output: Sara
let $price = 10;
console.log($price); // Output: 10
let _score = 42;
console.log(_score); // Output: 42
- Cannot start with a number. This is not allowed:
let 1day = 'Monday'; // Starts with a number, Uncaught SyntaxError: identifier starts immediately after numeric literal
- Also, don’t use JavaScript keywords like
let
,const
, orfunction
as variable names. This is not allowed:
let const = "Hello"; // Uncaught SyntaxError: unexpected token: keyword 'const
- Use camelCase for variable names — that means starting with a lowercase letter and capitalizing the first letter of each new word.
let userAge = 25;
console.log(userAge); // Output: 25
let isLoggedIn = true;
console.log(isLoggedIn); // Output: true
This makes your code easy to read for others—and for future-you!
Reassigning values
If you declared a variable with let
, you can change its value later:
let score = 50;
console.log(score); // Output: 50
score = 60;
console.log(score); // Output: 60
But if you used const
, trying to change the value will throw an error:
const maxUsers = 100;
console.log(score); // Output: 100
maxUsers = 200; // Error: Assignment to constant variable
So the rule is simple: use const
by default, and only switch to let
when you really need to update the value.