A program often needs to remember a value: how many fish, how much pocket money, a student's mark. For that we use a variable: a named box that holds a value, which we can change later.
You create (declare) a variable with let and a name, then put a value in it (assign) with =. To print its value, write its name inside console.log():
let fish; fish = 0; console.log(fish);
0
You can declare and assign in one line, which is the form you will use most: let fish = 0;
Updating a variable
The line fish = fish + 3; works from the right-hand side of =: take the current value of fish, add 3, then store the result back in fish. The old value is replaced by the new one.
let fish = 0;
fish = fish + 3;
fish = fish + 7;
console.log(fish);
console.log("fish");10 fish
"fish" in quotes prints the word fish itself.Using variables in output
A variable can hold a number or text (in quotes), and you use it in calculations and join it to text with + like any value. Choose clear names with no spaces, such as price or numberOfPeople, and remember that Price and price are different names.
let name = "Mona";
let price = 45;
let plates = 3;
console.log("Hello " + name);
console.log("Total: " + (price * plates) + " pounds");Hello Mona Total: 135 pounds
let only once, when the variable is created. To change it later, just use its name; repeating let with the same name causes an error:let apple = 5; let apple = 8; console.log(apple);
SyntaxError: Identifier 'apple' has already been declared
Practice
Declare the variable apple and assign it 0, then add 5 to it, then add 8, and print its value.
Press Run to see the result. Declare the variable allowance and assign it 700, then increase it by 1500, and print its value.
Press Run to see the result. Fill in the blank so it adds 10 to the variable number and the program prints 13.
let number; number = 3; number = ___; console.log(number);
Press Run to see the result. Declare the variable num and assign it 2 in one line, then add 8 to it, and print its value.
Press Run to see the result. This program prints the word score instead of the mark. Fix it so it prints 20.
let score = 18;
score = score + 2;
console.log("score");Press Run to see the result. You have 100 pounds in the variable money. You spend 35 on lunch, then your dad gives you 50. Update money after each step, then print Money left: 115.
Press Run to see the result. The school yard is a rectangle 8 long and 5 wide. Store them in the variables length and width, then print Area: 40 on one line and Perimeter: 26 on the next.
Hint
Area = length × width; perimeter = 2 × (length + width).Press Run to see the result. Key points
let x = 0;creates a variable and stores a value; writeletonly once.x = x + 3;takes the old value, adds 3 and stores the result in x.- A variable name without quotes gives its value, and can be joined to text:
"Total: " + x.