Variables
Names you give to values so the program can remember them.
A variable is a name attached to a value. Think of it as a labeled box: you put something in, and later you can ask for whatever is inside by saying its name.
Declaring a variable
In modern JavaScript there are two keywords you'll use:
let age = 30;
const name = "Ada";
letfor values that might change.constfor values that should not change (prefer this when you can).
You'll also see var in old code. Don't use it let and const behave better in almost every case.
Changing a value
let score = 0;
score = score + 10;
console.log(score); // 10
Trying to reassign a const is an error:
const pi = 3.14159;
pi = 3; // TypeError: Assignment to constant variable.
Naming rules
- Start with a letter,
_, or$. - No spaces. Use
camelCase:userName,totalScore. - Names are case-sensitive:
countandCountare different variables.
A quick exercise
Try this in your console:
const greeting = "Hello";
const target = "world";
console.log(greeting + ", " + target + "!");
What gets printed? Now change target to your own name and run it again.
Next up: making decisions with if.