A variable is a name for a value, so you can store it, use it later and change it when you need to. JavaScript has three keywords for creating variables: const, let and the older var. This lesson shows which to use and why.
Declaring a variable
You create, or declare, a variable with a keyword and a name, and usually give it a starting value with =:
const siteName = "Geeks2Smart";
let score = 0;
console.log(siteName);
// Geeks2Smart
console.log(score);
// 0
The = here is the assignment operator. It does not mean "equals" in the maths sense. It means "store the value on the right in the name on the left".
Once declared, you use the variable's name wherever you need its value:
const price = 12;
const quantity = 3;
const total = price * quantity;
console.log(total);
// 36
const: a name that always refers to the same value
const declares a variable that cannot be reassigned. Once it has a value, the name always refers to that value:
const maxAttempts = 3;
maxAttempts = 5;
// Uncaught TypeError: Assignment to constant variable.
A const must also be given a value when it is declared:
const greeting;
// Uncaught SyntaxError: Missing initializer in const declaration
That error message wording comes from Chrome. Firefox and Safari word it slightly differently, but every browser refuses.
let: a name you can reassign
let declares a variable you can give a new value later:
let score = 0;
score = score + 10;
score = score + 5;
console.log(score);
// 15
You can declare a let without a value. It then holds the special value undefined until you assign one:
let winner;
console.log(winner);
// undefined
winner = "Priya";
console.log(winner);
// Priya
You cannot declare the same name twice in the same block with let or const:
let total = 10;
let total = 20;
// Uncaught SyntaxError: Identifier 'total' has already been declared
This protects you from accidentally reusing a name that is already in use. Note that pasting both lines into the console at once shows this error, but some consoles relax the rule when you run the lines separately, to make experimenting easier. In a file, it is always an error.
Which one to choose
Use const by default. Switch to let only when you know the value will be reassigned, such as a counter or a running total.
This is not just a style choice. When you read code and see const, you know that name will refer to the same value for the rest of its block, without reading any further. When you see let, it is a signal: watch out, this changes. Most variables in well-written JavaScript turn out to be const.
const does not freeze values
const protects the name, not the value inside it. If a const holds an array or an object, you can still change what is inside it:
const scores = [10, 20];
scores.push(30);
console.log(scores);
// [10, 20, 30]
scores = [];
// Uncaught TypeError: Assignment to constant variable.
Adding an item to the array is allowed, because scores still refers to the same array. Pointing scores at a different array is not. You will learn about arrays and objects in lessons 12 and 13, and about freezing objects later in the course.
Block scope
let and const are block scoped. A block is any code between curly braces { }, such as the body of an if statement. A variable declared inside a block only exists inside it:
const temperature = 25;
if (temperature > 20) {
const message = "Warm today";
console.log(message);
// Warm today
}
console.log(message);
// Uncaught ReferenceError: message is not defined
Keeping variables inside the smallest block that needs them makes code easier to follow, because each name only matters in one place. Lesson 19 covers scope in full.
Why var is avoided
Before 2015, var was the only way to declare a variable. You will still see it in older code and tutorials, so you need to recognise it:
var city = "Leeds";
city = "York";
var has three behaviours that cause bugs.
It ignores blocks. A var declared inside an if or a loop is visible outside it, throughout the whole function:
if (true) {
var leaked = "I escaped the block";
}
console.log(leaked);
// I escaped the block
It can be redeclared silently. Declaring the same name twice gives no error, so you can overwrite a variable without noticing:
var count = 1;
var count = 2;
console.log(count);
// 2
It is usable before its declaration. A var is created at the start of its function with the value undefined, so reading it too early gives undefined instead of an error:
console.log(colour);
// undefined
var colour = "teal";
With let or const, the same mistake throws an error that points straight at the problem. That is much better: a loud error is easier to fix than a quiet wrong value.
Because let and const are better in every case, do not use var in new code. Lesson 19 explains the rules behind these differences, called hoisting and the temporal dead zone.
Assigning to a name that was never declared, such as total = 5; with no keyword, creates a global variable in old-style scripts. In modules and strict mode it throws a ReferenceError instead. Always declare variables with const or let.
Naming variables
Names can contain letters, digits, _ and $, but cannot start with a digit. They are case-sensitive, so score and Score are different variables. You cannot use reserved words such as let, class, return or if as names.
JavaScript developers follow a few conventions:
- camelCase for variables and functions:
firstName,totalPrice,isLoggedIn. - UPPER_SNAKE_CASE for fixed configuration values known before the program runs:
MAX_ATTEMPTS,API_TIMEOUT_MS. Not everyconstneeds capitals; aconstholding a calculated result is still camelCase. - Booleans read well with
is,hasorcan:isVisible,hasErrors,canEdit.
Choose names that describe what the value means, not its type:
// Unclear
const d = 7;
const arr = ["Ada", "Grace"];
// Clear
const daysUntilDeadline = 7;
const speakerNames = ["Ada", "Grace"];
Short names such as i are fine for a loop counter that lives for three lines. Anything that lives longer deserves a descriptive name. You will read your code many more times than you write it.
Summary
- Declare variables with
constby default, andletwhen the value must be reassigned. conststops reassignment of the name, but the contents of arrays and objects can still change.letandconstare block scoped and cannot be redeclared in the same block.- Avoid
var: it ignores blocks, allows silent redeclaration and givesundefinedinstead of an error when used too early. - Always declare a variable before using it.
- Use descriptive camelCase names, and
is,hasorcanfor booleans.