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.
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 againRead 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.
- Value: 250
- Value: "Wanjiru"
- Value: false
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:
| Type | What it holds | Examples in JavaScript | What you can do |
|---|---|---|---|
| Number | Whole or decimal numbers | 42, 3.5, -7 | Add, subtract, multiply, compare |
| String | Text, written inside quotation marks | "Amina", 'hello', "42" | Join together, measure length |
| Boolean | Only true or false | true, false | Use 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.
SET age TO 17
IF age is less than 18
SHOW "Student discount applies"
ELSE
SHOW "Full price"
END IFIn 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.
let age = 17;
if (age < 18) {
console.log("Student discount applies");
} else {
console.log("Full price");
}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.
- Is age less than 18?
- YesDo thisShow: Student discount applies
- NoDo thisShow: Full price
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.
REPEAT for each number from 1 to 3
SHOW the number
END REPEATThe 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.
for (let i = 1; i <= 3; i++) {
console.log(i);
}1
2
3Functions: 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.
function addTax(price) {
return price * 1.16;
}
let shirt = addTax(1000); // shirt now holds 1160
let book = addTax(500); // book now holds 580Reading 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.
- Step 1: Inputprice = 1000
- Step 2: addTaxprice * 1.16
- Step 3: Outputreturns 1160
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.
- let total = 750;
- What is stored?
- if (age < 18) {...}
- Which way do we go?
- for (...) {...}
- How many times?
- function addTax(...)
- How do I reuse this?
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,aandthing.✔ 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
letline. Check the spelling and the capital letters, becausePriceandpriceare different names. - My if statement always takes the same path.
- Print the value you are checking with
console.logjust before theif. 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.
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.
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.
Knowledge check
6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.
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.
- JavaScript first steps (MDN Web Docs)
- Variables (glossary) (MDN Web Docs)
- Functions (glossary) (MDN Web Docs)