Find a course

Module 4: Programming FundamentalsLesson 9 of 1214 min

Variables, Conditions and Loops

Write your first JavaScript: store values in variables, understand data types, make decisions with if statements and repeat work with for and while loops.

Step 1 of 16Learn

Variables: named boxes for values

A program needs to remember things: a player's score, a username, the items in a shopping cart. It stores them in variables, named places in memory that hold values.

In JavaScript you create a variable with let (for values that change) or const (for values that stay the same):

let score = 0;
const playerName = "Ada";
score = score + 10;   // score is now 10

That last line confuses many beginners. In math, "score = score + 10" is impossible. In programming, = means assignment: compute the right side, then store the result in the variable on the left. So it reads "set score to its current value plus 10." To compare values, JavaScript uses === (equal) and !== (not equal).

Every value has a data type. The most common are:

  • Number: 42, 3.14, -7
  • String (text, in quotes): "hello", "42"
  • Boolean: true or false
  • Array (an ordered list): [3, 1, 4]

Types matter because operations behave differently. In JavaScript, 5 + 3 is 8, but "5" + 3 is the string "53", because + joins strings together. Many bugs come from text that looks like a number but isn't, such as input typed by a user.

Good variable names make code readable. totalPrice beats tp or x every time.

Step 2 of 16Practice · Work it out

What is the value of n after this code runs? let n = 4; n = n * 2; n = n + 3; n = n - 1;

Step 3 of 16Compare

let vs const

Aspectletconst
Can be reassigned?Yes: score = score + 10No: reassigning throws an error
Use forCounters, totals, changing stateNames, settings, values that stay fixed
Examplelet lives = 3;const maxLives = 5;
Good habitUse when you know it will changeDefault choice; switch to let if needed

Step 4 of 16Practice · Match the pairs

Match each JavaScript value with its data type.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. 42
  2. "42"
  3. false
  4. [42, 7, 19]

Step 5 of 16Learn

Making decisions with if

Programs make choices with if statements, the code version of selection:

if (temperature > 30) {
  message = "Hot";
} else if (temperature > 15) {
  message = "Mild";
} else {
  message = "Cold";
}

The condition in parentheses must evaluate to true or false. JavaScript checks the conditions from top to bottom and runs only the first block whose condition is true. If none match, the else block runs.

Conditions use comparison operators:

OperatorMeaning
===equal to
!==not equal to
> and <greater than, less than
>= and <=at least, at most

You can combine conditions with logical operators, the Boolean logic from the previous module: && (AND), || (OR) and ! (NOT).

if (age >= 13 && hasPermission) { allowSignup(); }

Watch out for the classic mistake of writing a single = inside a condition. if (x = 5) assigns 5 to x instead of comparing, and the condition is treated as true. Use === for comparisons.

Step 6 of 16Practice · Diagram

Which message does each temperature get?

Using the code above: > 30 is "Hot", otherwise > 15 is "Mild", otherwise "Cold". Watch the boundaries.

Which temperature is the highest one that still gets "Mild"? Tap it.

Tap the shape that answers the question, then press Check.

Which message does each temperature get?Scale: 10, 15, 30, 35.ColdMildHot051015202530354010 °C1015 °C1530 °C3035 °C35
10

10 °C

15

15 °C

30

30 °C

35

35 °C

Step 7 of 16Note

Step 8 of 16Practice · Code challenge

Write ticketPrice(age) that returns the price of a movie ticket: 8 for children under 12, 5 for seniors aged 65 or over, and 12 for everyone else.

Runs in a sandbox in your browser.
  • ticketPrice(8)
  • ticketPrice(12)
  • ticketPrice(40)
  • ticketPrice(65)
  • ticketPrice(80)

Step 9 of 16Learn

Repeating with loops

Computers are great at doing the same thing many times without getting bored. Loops handle iteration.

A for loop is ideal when you know how many times to repeat:

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

The header has three parts: start (let i = 1), the condition to keep going (i <= 5), and the update after each round (i++, which adds 1). This prints 1, 2, 3, 4, 5.

A while loop repeats as long as a condition stays true, which suits situations where you don't know in advance how many rounds you'll need:

let balance = 1000;
let years = 0;
while (balance < 2000) {
  balance = balance * 1.07;
  years++;
}

This counts how many years it takes $1,000 to double at 7% growth (the answer is 11).

Two loop bugs to watch for:

  • Infinite loops: if the condition never becomes false (say you forget years++ and the condition depended on it), the program runs forever.
  • Off-by-one errors: i < 5 runs for i = 0 to 4 (five times starting at 0), while i <= 5 starting at 0 runs six times. Trace the first and last rounds to be sure.

Step 10 of 16Diagram

How a for loop runs

How a for loop runsCycle diagram: Init: let i = 1 → Check condition → Run the body → Update: i++.for (init;condition;update)Init: let i = 1Check conditionRun the bodyUpdate: i++

Tap a shape with to see more.

Init: let i = 1

Runs once, before the first check.

Check condition

If false, the loop ends here.

Run the body
Update: i++

Then back to the check.

Step 11 of 16Note

Step 12 of 16Practice · Work it out

How many times does the body of this loop run? for (let i = 0; i < 10; i += 2) { ... }

Step 13 of 16Practice · Code challenge

Write sumTo(n) that returns the sum 1 + 2 + ... + n using a loop. For example, sumTo(4) is 10. If n is 0, return 0.

Runs in a sandbox in your browser.
  • sumTo(4)
  • sumTo(1)
  • sumTo(0)
  • sumTo(100)

Step 14 of 16Note

Step 15 of 16Practice · Spot the mistake

This code should print the numbers 1 to 5. Tap the line that contains the bug.

Step 16 of 16Practice · Choose one

What does "7" + 3 produce in JavaScript?