Variables
JavaScript · Unit 1: First steps
- Free
- JavaScript
- 11 exercises
With let you create a variable you can change later.
With const, one that doesn't change.
let age = 17;
age = age + 1;
console.log(age);Prints
18
To change the value of a let, use = again: the new one replaces the old one.
You can even use the current value to work out the new one. A const can't be changed.
let points = 10;
points = 25;
console.log(points);
points = points + 5;
console.log(points);Prints
25 30
let b = a copies into b the value that a has at that moment.
After that they're independent: if you change a, b stays the same.
let today = 20;
let yesterday = today;
today = 25;
console.log(yesterday, today);Prints
20 25
Names take letters and numbers, can't start with a number and take no spaces or dashes.
To join words you stick the next one on with a capital: myAge. That's camelCase.
const myAge = 17;
const totalPrice = 250;
console.log(myAge, totalPrice);Prints
17 250
Every instruction ends with a semicolon.
JavaScript almost always puts it in for you if you forget, but writing it avoids surprises.
const name = "Chloe";
console.log(name);Prints
Chloe
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
const fruit = "apple"; console.log("fruit"); console.log(fruit);2. Complete the code
Fill in to create the variable the greeting uses.
const ___ = "Owen"; console.log("Hello,", name);3. Put the lines in order
Order the lines to say hello to Emma.
4. Predict the output
What does this code print?
let weather = "sunny"; console.log("Today:", weather); weather = "rainy";5. Complete the code
Noah won 5 more points. Fill in so his score goes up.
let points = 20; points = ___ + 5; console.log(points);6. Find the bug
This program should subtract the discount from the price. Which line has the error?
const price = 100; const discount = 20; const total = price + discount; console.log("Total to pay:", total);7. Multiple choice
Which word do you use to declare a variable you are NOT going to reassign?
8. Predict the output
What does this code print?
let x = 5; let y = x; x = 10; console.log(y);9. Find the bug
This program should print Sophie's final grade. Which line has the error?
const final grade = 85; console.log("Grade:", finalGrade);10. Multiple choice
What happens if you forget the semicolon at the end of a line?
11. Predict the output
Follow each variable line by line. What does it print?
let mug = "tea"; const glass = "coffee"; mug = glass; console.log(mug, glass);
It opens in your browser. It is free and you do not need an account to start.