Chapters

FundamentalsChapter 7 of 21

Variables

Names that point at values, and how to choose between const and let.

Naming a value

A variable is a name pointing at a value. You make one by declaring it, with const or let:

JavaScript

JavaScript

const name = 'Ada';
let age = 36;

age = age + 1;

console.log(name, age);

Output

Ada 37

Read = as "refers to", not "equals". The name on the left starts pointing at whatever the right side produced.

const by default

Reach for const first and switch to let only when you actually need to reassign. A reader then knows at a glance which names change, which is most of the value.

JavaScript

JavaScript

const taxRate = 0.19;
let runningTotal = 0;

runningTotal = runningTotal + 100;
runningTotal = runningTotal * (1 + taxRate);

console.log(runningTotal.toFixed(2));

Output

119.00

Declare before you use

Using a name before its declaration is an error, and a helpfully specific one:

JavaScript

JavaScript

try {
  console.log(score);
  let score = 10;
} catch (error) {
  console.log(error.name + ': ' + error.message);
}

Output

ReferenceError: Cannot access 'score' before initialization

The name exists from the top of its block but cannot be touched until the declaration runs. That gap has a name, the temporal dead zone, and it exists to turn a silent undefined into a loud error.

One name, one job

A variable can hold any type, and reusing one name for unrelated things makes code hard to follow. Declare a new name instead; they are free.

JavaScript

JavaScript

const priceText = '42';
const price = Number(priceText);

console.log(typeof priceText, typeof price);

Output

string number

Naming

Names are read far more often than they are written. daysUntilRenewal costs nothing over d and answers a question the reader would otherwise have to work out.

  • camelCase for variables and functions.
  • Say what it holds, not what type it is: customer, not customerObject.
  • Booleans read well with is, has or should: isReady, hasAccess.
  • Short names are fine in short scopes, such as the index in a loop.

Test yourself

2 questions

When should you use let instead of const?

Show the answer

Only when the name is reassigned const marks a name that never points somewhere else, which tells the reader a lot for free.

What happens if you read a let variable before its declaration?

Show the answer

A ReferenceError The temporal dead zone turns what would be a silent undefined into an error you can see.

Next chapter

let

A name you can reassign, scoped to the block it lives in.