Chapter 02
Values & Variables
A value is a single piece of information: the number 7, the text "hello", the idea of true or false. Programs are mostly about moving values around and changing them.
But a value on its own is easy to lose. If you want to use the same value later, you give it a name. A named value is called a variable - think of it as a labelled box you can put a value into and fetch again whenever you need it.
Creating a Variable
You create a variable with the word let, a name, an equals sign, and a value:
let age = 25;
console.log(age); // 25Read that as: "let the box named age hold the value 25." From now on, whenever you write age, JavaScript swaps in whatever is inside that box.
= does not mean "is equal to" like in maths. It means "put the value on the right into the box on the left." We call this assignment. (Checking whether two things are equal uses a different symbol - Chapter 4.)Changing a Variable
A variable made with let can be changed later. Just assign a new value - no need to write let again:
let score = 0;
console.log(score); // 0
score = 10;
console.log(score); // 10
score = score + 5;
console.log(score); // 15That last line looks strange at first. Remember the right side runs first: score + 5 is 10 + 5, which is 15, and that result is put back into score. Updating a variable using its own current value is extremely common.
Values That Never Change: const
Sometimes a value should never change - the number of days in a week, a tax rate, your date of birth. For those, use const instead of let. A const cannot be reassigned:
const daysInWeek = 7;
console.log(daysInWeek); // 7
daysInWeek = 8; // Error! Assignment to constant variable.const first. Only switch to let when you know the value genuinely needs to change. This makes your intentions clear and stops accidental changes.Naming Your Variables
Names should describe what they hold. x tells you nothing; numberOfStudents tells you everything. The rules:
- Start with a letter (or
_/$), then letters or numbers. No spaces. - They're case-sensitive:
ageandAgeare two different boxes. - When a name has several words, capitalise each word after the first:
firstName,totalPrice. This style is called camelCase and it's the convention in JavaScript.
const firstName = "Ada";
let itemsInCart = 3;
const pricePerItem = 4.99;
console.log(firstName, itemsInCart, pricePerItem); // Ada 3 4.99Notice console.log can print several values at once if you separate them with commas.