Declaring Variables
Objectives
By the end of this chapter, you should be able to:
- Declare variables with
constandlet - Explain why
constis the default choice and when to reach forlet - Recognize
varin older code and explain why modern code avoids it - Name variables following JavaScript’s rules and the camelCase convention
💡 Why this matters: Variables are how your program remembers anything: a name, a total, a score. Almost every line of code you write from here on touches one.
Declaring a Variable with const
A variable is a named container for a value. You create one with a declaration: a keyword, a name, and the value to store.
const name = "Maya";
console.log(name);
// Maya
const stands for “constant.” Once you assign a value with const, you cannot assign that variable a different value later.
const age = 30;
age = 31;
// TypeError: Assignment to constant variable.
That error is a feature, not an annoyance. If a value is never supposed to change (a person’s birth year, the number of days in a week), const stops you from accidentally overwriting it somewhere else in your code.
Use const by default for every variable you declare. Only switch to let when you have a specific reason to reassign the value.
Declaring a Variable with let
let also declares a variable, but it allows reassignment.
let score = 0;
console.log(score);
// 0
score = 10;
console.log(score);
// 10
Use let for values that genuinely change over the life of your program: a running total, a counter, a status that switches between “loading” and “done.”
let attempts = 0;
attempts = attempts + 1;
console.log(attempts);
// 1
A variable declared with let (or const) can only be declared once in the same scope. Declaring it twice is an error:
let city = "Nairobi";
let city = "Kampala";
// SyntaxError: Identifier 'city' has already been declared
var: The Old Way
Before let and const existed (they arrived in ES6, 2015), JavaScript had only one way to declare a variable: var. You’ll still see var in older code and tutorials, so it’s worth recognizing, but modern code avoids it for two reasons.
1. var ignores block scoping. A “block” is anything inside { }, like the body of an if statement. Variables declared with let or const only exist inside the block where they’re declared. var leaks out of the block entirely:
if (true) {
var leaked = "I'm out here too";
let contained = "I stay inside";
}
console.log(leaked);
// I'm out here too
That leaking makes it easy to lose track of where a variable is actually meant to be used, especially in longer programs.
2. var allows silent redeclaration. Declaring the same var name twice doesn’t error, it just quietly overwrites:
var total = 100;
var total = 200;
console.log(total);
// 200
With let or const, that same mistake throws an error immediately, which helps you catch it instead of debugging a mystery later. This course uses const and let exclusively. Treat var as something to recognize in old code, not something to write.
Naming Variables
JavaScript variable names must follow a few rules:
- Can contain letters, digits,
_, and$. - Cannot start with a digit.
- Cannot be a reserved word (
let,const,if,function, and so on). - Are case-sensitive:
totalandTotalare different variables.
const price1 = 9.99;
const _hidden = true;
const $element = "allowed, but unusual outside libraries";
const 1stPlace = "Erin";
// SyntaxError: Invalid or unexpected token
Beyond what’s legal, JavaScript convention is camelCase: the first word lowercase, every following word capitalized, no spaces or underscores.
const firstName = "Jordan";
const totalScore = 95;
const isLoggedIn = true;
Pick names that describe what the value actually is. firstName tells the next reader (often future you) far more than x or data.
// Unclear
const x = 42;
// Clear
const userAge = 42;
Try It
- Declare a
constcalledfavoriteColorand assign it a string. Log it. - Declare a
letcalledpointsstarting at0. Reassign it to5, then log it. - Try reassigning a
constafter it’s declared and read the error Node gives you. - Write three variable names in camelCase for: a user’s email, whether a task is complete, and a shopping cart total.
Recap
constdeclares a variable that cannot be reassigned. Use it by default.letdeclares a variable that can be reassigned. Use it when a value needs to change.varis the old way to declare variables. It ignores block scoping and allows silent redeclaration, so modern code avoids it.- Variable names follow camelCase and should describe what they hold.
Next lesson: the core data types JavaScript works with, and how to check the type of any value.