The Academy

Loading the search index…

Searches the academy on this device only.

Variables, data types, conditions, loops and functions

Meet the four building blocks found in almost every program: variables that hold values, conditions that choose, loops that repeat and functions that package a job, first in pseudocode and then in JavaScript.

30 minbeginner

Marking a lesson as read does not prove you can do it. Skills count as demonstrated when you pass the quiz (not yet) and complete the practical tasks (not yet).

By the end of this lesson you will be able to

  • Explain a variable as a named box that holds a value, and say how its value can change.
  • Name the main data types (number, string, boolean) and give an example of each.
  • Write an if and else decision in pseudocode and read the same decision in JavaScript.
  • Describe what a loop does and read a short for loop.
  • Explain why a function is useful and read a function with a parameter and a return value.

Almost every program, from a calculator to a banking website, is built from the same few ideas. Programs remember things, make choices, repeat work and package tasks into reusable pieces. Once you can recognise these four building blocks you will be able to read simple code in any language, because the ideas stay the same while the spelling changes. This lesson introduces them in plain pseudocode first, and then shows how they look in JavaScript, the language that makes web pages interactive.

Variables: named boxes for values

A Variable is a named place in the computer's memory that holds a value. Picture a labelled box. The label is the variable's name, such as price, and what is inside is its value, such as 250. You can look inside, and you can replace what is inside with something else, which is why it is called a variable: its value can vary.

Good names matter. price tells the next reader what is stored, while x does not. Names usually use no spaces, so programmers join words, for example totalPrice. In pseudocode we write SET price TO 250. In JavaScript the same idea is written with the word let and an equals sign, which means "store the value on the right into the name on the left". It does not mean "is equal to" as in school maths.

JavaScript
let price = 250;
let quantity = 3;
let total = price * quantity;

price = 300;   // the box now holds 300
// total still holds 750 until we work it out again
Creating and changing a variable (JavaScript)

Read it like a story. Line 1 makes a box called price and puts 250 in it. Line 3 multiplies the two values and stores the answer, 750, in total. Line 5 replaces the value in price with 300, but total is not recalculated, because the computer only does what each line says, once, in order. The words after // are a comment: notes for people that the computer ignores.

Diagram

Each variable has a name, a type of value and the value itself.

pricetype: number
  • Value: 250
customertype: string
  • Value: "Wanjiru"
isPaidtype: boolean
  • Value: false
Each variable has a name, a type of value and the value itself.
Read this figure as text

Three labelled boxes showing variables named price, name and isPaid with their values and types.

Three variables are shown as boxes. The box named price holds the number 250. The box named customer holds the text "Wanjiru". The box named isPaid holds the value false. Each box shows the name on top, the value inside and the type underneath: number, string and boolean.

Data types: what kind of value is it?

Values come in kinds, and each kind is called a data type. The computer treats each kind differently, just as you treat a phone number differently from a price. The three you will use most are:

The three most common data types
TypeWhat it holdsExamples in JavaScriptWhat you can do
NumberWhole or decimal numbers42, 3.5, -7Add, subtract, multiply, compare
StringText, written inside quotation marks"Amina", 'hello', "42"Join together, measure length
BooleanOnly true or falsetrue, falseUse in conditions to choose a path

Conditions: making choices

A Condition is a question that is either true or false, used to decide which steps to run. You met this as the umbrella example in the last lesson. The pseudocode below checks whether a customer qualifies for a student discount.

Text
SET age TO 17
IF age is less than 18
    SHOW "Student discount applies"
ELSE
    SHOW "Full price"
END IF
Pseudocode: a choice with IF and ELSE

In JavaScript the question goes in round brackets after if, and the steps to run go in curly brackets. The comparison symbols are < (less than), > (greater than), === (exactly equal) and !== (not equal). Notice there are three equals signs when comparing. One = stores a value; === asks a question.

JavaScript
let age = 17;

if (age < 18) {
  console.log("Student discount applies");
} else {
  console.log("Full price");
}
The same choice in JavaScript

console.log shows a message in the browser's developer console, which you will meet in a later module. For now think of it as "SHOW". When this code runs it prints Student discount applies, because 17 is less than 18.

Diagram

An if and else decision follows exactly one of two paths.

  • Is age less than 18?
    • YesDo thisShow: Student discount applies
    • NoDo thisShow: Full price
An if and else decision follows exactly one of two paths.
Read this figure as text

A decision diagram asking whether age is less than 18, with a discount outcome for yes and full price for no.

The question is "Is age less than 18?". If yes, the program shows "Student discount applies". If no, it shows "Full price". Only one of the two paths is followed each time the program runs.

Loops: repeating without retyping

A Loop repeats steps until a stopping rule is met. Without loops, showing a message 100 times would need 100 lines. With a loop it needs three. Loops are the reason computers are so good at boring, repetitive work.

Text
REPEAT for each number from 1 to 3
    SHOW the number
END REPEAT
Pseudocode: repeat a fixed number of times

The JavaScript for loop has three parts inside its brackets, separated by semicolons: where to start (let i = 1), when to keep going (i <= 3) and what to do after each round (i++, which means add one to i). The variable i is just a counter.

JavaScript
for (let i = 1; i <= 3; i++) {
  console.log(i);
}
A for loop that counts from 1 to 3
Text
1
2
3
What this prints, one number per line

Functions: reusable named jobs

A Function is a named block of steps that you can run whenever you need it. Think of a recipe card in a drawer. You write the recipe once, give it a name, and then use it again and again. A function can receive values to work with, called parameters, and can give back an answer, called the return value.

JavaScript
function addTax(price) {
  return price * 1.16;
}

let shirt = addTax(1000);   // shirt now holds 1160
let book = addTax(500);     // book now holds 580
A function that works out a price with 16 per cent tax

Reading it step by step: function addTax(price) defines a job called addTax that takes one parameter named price. The line return price * 1.16; hands back the answer. Further down we call the function twice with different values and store each answer in a variable. We wrote the calculation once and used it twice. If the tax rate changes, we fix one line instead of many.

Diagram

A function takes inputs, does its steps and gives back an output.

  1. Step 1: Inputprice = 1000
  2. Step 2: addTaxprice * 1.16
  3. Step 3: Outputreturns 1160
A function takes inputs, does its steps and gives back an output.
Read this figure as text

A flow showing the number 1000 going into the function addTax and the number 1160 coming out.

Three steps joined by arrows. Step 1: input, the value 1000 is passed in as the parameter price. Step 2: the function addTax multiplies price by 1.16. Step 3: output, the value 1160 is returned and stored in the variable shirt.

The tax rate used here is an invented example for practice, not advice about real tax. Put the four ideas together and you can read most beginner programs: values are stored in variables, conditions choose, loops repeat and functions package jobs.

Diagram

The four building blocks and what each one is for.

VariablesRemember
  • let total = 750;
  • What is stored?
ConditionsChoose
  • if (age < 18) {...}
  • Which way do we go?
LoopsRepeat
  • for (...) {...}
  • How many times?
FunctionsReuse
  • function addTax(...)
  • How do I reuse this?
The four building blocks and what each one is for.
Read this figure as text

Four columns naming variables, conditions, loops and functions with the question each answers.

Variables remember a value and answer the question "what is stored?". Conditions choose a path and answer "which way do we go?". Loops repeat steps and answer "how many times?". Functions package steps under a name and answer "how do I reuse this job?".

Common mistakes

  • ✖ Instead of: Using one equals sign in a question, such as if (age = 18).

    ✔ Do this: Use === to compare. A single = stores a value and does not ask a question.

  • ✖ Instead of: Putting numbers in quotation marks and expecting to add them.

    ✔ Do this: Leave quotation marks off numbers. "4" + "2" joins text to make "42".

  • ✖ Instead of: Naming variables x, a and thing.

    ✔ Do this: Use names that say what the value is, such as ticketPrice, so you and others can read the code later.

  • ✖ Instead of: Writing a loop with no way to reach its stopping rule.

    ✔ Do this: Check that something inside or after each round moves towards the stopping condition, such as i++.

If something goes wrong

The browser console says ReferenceError: price is not defined.
The name is spelt differently from where you created it, or you used it before the let line. Check the spelling and the capital letters, because Price and price are different names.
My if statement always takes the same path.
Print the value you are checking with console.log just before the if. Often the variable holds a string such as "17" or an unexpected value, so the comparison is not asking what you think.
The tab froze while I tried a loop.
The loop probably never stops. Close the tab, reopen the page and check that your counter changes each round and that the stopping rule can become false.

Key terms

Variable
A named box in a program that holds a value which can change.
data type
A data type is the kind of thing a cell holds, such as text, a number or a date.
String
A piece of text in a program, written between quotation marks.
Condition
A test in a program that is either true or false and decides what happens next.
Loop
A part of a program that repeats instructions again and again.
Function
A named block of instructions in a program that you can reuse whenever needed.

Practise it for real

Reading is not the same as being able to do it. Complete these on your own computer, then tick only what you have actually done. These ticks are your own honest record: nothing checks them for you.

Guided exercise

Predict what the code prints

On paper, work out what each piece of code would print without running it. (a) let n = 5; if (n > 3) { console.log("big"); } else { console.log("small"); } (b) for (let i = 2; i <= 4; i++) { console.log(i * 10); } (c) function double(x) { return x * 2; } console.log(double(7)); Write your three answers and one sentence for each saying which building block it used.

You have succeeded when:
Independent challenge

Challenge: plan a ticket price checker

Plan, in pseudocode only, a small program for a fictional cinema. It stores the age of a visitor in a variable. Children under 12 pay 300 shillings and everyone else pays 500. The program shows the price. Then add a loop that shows the price line for ages 10, 11, 12 and 13. Name your variables sensibly and add a comment line explaining the rule.

You have succeeded when:

Knowledge check

6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.

  1. Question 1.After this code runs, what does score hold? let score = 10; score = score + 5;
  2. Question 2.Match each value to its data type.
  3. Question 3.In JavaScript, a single equals sign (=) is used to store a value, while three equals signs (===) are used to compare two values.
  4. Question 4.Joseph needs a program that shows a welcome message to 200 guests, one name at a time.Which building block saves him from writing 200 separate lines?
  5. Question 5.What is the main benefit of putting a calculation into a function?
  6. Question 6.Put these in the order they happen when for (let i = 1; i <= 2; i++) { console.log(i); } runs.
    1. i is set to 1
    2. The check 3 <= 2 fails and the loop ends
    3. 1 is printed and i becomes 2
    4. 2 is printed and i becomes 3

Summary

  • A variable is a named box holding a value that can change.
  • Common data types are number, string (text in quotes) and boolean (true or false).
  • Conditions use if and else to choose one path.
  • Loops repeat steps until a stopping rule is met.
  • Functions package steps under a name, take parameters and return a result.

Checklist: can you do these?

Marking a lesson as read does not prove you can do it. Skills count as demonstrated when you pass the quiz (not yet) and complete the practical tasks (not yet).

Related lessons

References and further reading

Official sources for details that can change between versions.

On this page