By the end of this lesson you will be able to
- Declare variables with let and const and choose between them.
- Write an if / else if / else decision using comparison operators.
- Use a for loop and a for...of loop to repeat work.
- Write a function with parameters that returns a value.
- Store lists in arrays and named values in objects, and read items from them.
In the earlier programming lessons you met variables, conditions, loops and functions as ideas. Now you will write them in JavaScript, the language every web browser can run. It is the third part of the web trio: HTML gives a page its structure, CSS its looks and JavaScript its behaviour. Nothing you write here can harm your computer, because the code runs inside the browser's protected space, and the practice lab below needs nothing installed.
Where JavaScript runs and how to see results
JavaScript is a programming language built into browsers. When a page loads, the browser reads the HTML, the CSS and any scripts, and runs the scripts line by line from top to bottom. To see what your code does you need somewhere to show output. The simplest way is console.log(...), which prints a value to the Console, a panel in the browser's developer tools that you will meet properly in the third lesson of this module.
You can also put a script in an HTML page with a script element. Anything between the tags is JavaScript. Lines starting with // are comments: notes for humans that the computer ignores.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>First script</title>
</head>
<body>
<h1>Hello</h1>
<script>
// This line prints to the console.
console.log("The script ran.");
</script>
</body>
</html>Variables: named boxes for values
A Variable is a named place that holds a value. In modern JavaScript you create one with let when the value will change later, and with const when it will not. A good habit is to start with const and switch to let only when you need to. The equals sign does not mean "is equal to" here: it means "put the value on the right into the name on the left".
letKeywordCreates a variable scoreNameYou choose it = AssignPut value into name10ValueA number;SemicolonEnds the statementRead this figure as text
The statement let score = 10; split into keyword, name, equals sign, value and semicolon.
The statement let score = 10; is split into five labelled parts. let is the keyword that creates a changeable variable. score is the name you choose. The equals sign means put the value into the name. 10 is the value, a number. The semicolon ends the statement.
Values have types. The three you meet first are numbers (42, 3.5), strings (text in quotation marks, such as "Amina") and booleans (true or false). You can join strings with + or, more neatly, with a template literal: text between backticks with ${name} slots.
const gardener = "Wanjiru"; // a string, will not change
let seedsPlanted = 12; // a number, will change
const isOpen = true; // a boolean
seedsPlanted = seedsPlanted + 5;
console.log(`${gardener} has planted ${seedsPlanted} seeds.`);
console.log(typeof seedsPlanted);Wanjiru has planted 17 seeds.
numberConditions: making decisions
A Condition is a question with a true or false answer. if runs a block of code only when the condition is true; else if and else cover the other cases. Comparisons use >, <, >=, <=, === (is exactly equal to) and !== (is not equal to). Always use three equals signs to compare: a single = assigns and would overwrite your variable. Combine conditions with && (and) and || (or).
const temperature = 31;
if (temperature >= 35) {
console.log("Too hot: water the beans twice.");
} else if (temperature >= 20) {
console.log("Warm: water the beans once.");
} else {
console.log("Cool: no extra water.");
}- temperature >= 35 ?
- YesDo thisWater twice
- Notemperature >= 20 ?
- YesDo thisWater once
- NoDo thisNo extra water
Read this figure as text
A decision tree asking whether the temperature is 35 or more, then 20 or more, with three results.
Start with the question: is temperature 35 or more? If yes, the result is Too hot: water twice. If no, ask: is temperature 20 or more? If yes, the result is Warm: water once. If no, the result is Cool: no extra water. With temperature 31, the first answer is no and the second is yes, so the program prints the Warm message.
Loops: repeating work
A Loop repeats a block of code. The classic for loop has three parts inside its brackets, separated by semicolons: where to start (let i = 1), when to keep going (i <= 5) and what to do after each round (i++, which adds one). A while loop repeats as long as a condition stays true; take care that something inside it eventually makes the condition false, or it will never stop and the browser tab will freeze.
for (let i = 1; i <= 5; i++) {
console.log("Row " + i);
}
let water = 3;
while (water > 0) {
console.log("Litres left: " + water);
water = water - 1;
}Functions: code you can reuse
A Function is a named block of code you can run whenever you like. It can take parameters (inputs written inside the brackets) and can return a result. Defining a function does not run it; you run it by writing its name followed by brackets, which is called calling it. Functions save you repeating yourself and give pieces of code a clear purpose.
function greet(name) {
return "Hello, " + name + "!";
}
const total = (price, quantity) => price * quantity;
console.log(greet("Joseph"));
console.log(total(250, 4));Hello, Joseph!
1000The second function uses the shorter arrow function style, which you will see often. Both do the same job here.
Arrays and objects: collections of values
An Array is an ordered list written in square brackets. Items are numbered from zero, so the first item is list[0]. The property list.length gives how many items there are, and list.push(x) adds one at the end. An object keeps named values, called properties, in curly brackets and you read one with a dot: person.name. Real programs mix them: an array of objects is a table of records.
- ["bean", "maize", "kale"]
- 0 is bean, 1 is maize, 2 is kale
- seeds[1] gives maize
- seeds.length gives 3
- { name: "North bed", rows: 4 }
- name is North bed
- plot.rows gives 4
- plot.name gives North bed
Read this figure as text
Two columns comparing an array found by position numbers with an object found by property names.
Two columns. Array: const seeds = ["bean", "maize", "kale"]. Position 0 holds bean, position 1 holds maize, position 2 holds kale. You read an item with seeds[1], which gives maize. Object: const plot = { name: "North bed", rows: 4 }. The property name holds North bed and the property rows holds 4. You read an item with plot.rows, which gives 4.
const beds = [
{ name: "North bed", rows: 4 },
{ name: "East bed", rows: 6 },
];
let totalRows = 0;
for (const bed of beds) {
console.log(bed.name + " has " + bed.rows + " rows");
totalRows = totalRows + bed.rows;
}
console.log("Total rows: " + totalRows);North bed has 4 rows
East bed has 6 rows
Total rows: 10Try it yourself
Work through the short challenges. Each one checks your answer instantly. The code runs inside your browser and cannot touch your files.
Loading lab…
Common mistakes
✖ Instead of: Using
=inside anifcondition to compare values.✔ Do this: Use
===to compare. A single=assigns a value and changes your variable.✖ Instead of: Expecting the first array item to be
list[1].✔ Do this: Arrays start at zero. The first item is
list[0]and the last islist[list.length - 1].✖ Instead of: Writing a
whileloop that never changes its condition.✔ Do this: Make sure something inside the loop moves it towards finishing, such as subtracting from a counter.
✖ Instead of: Defining a function and then wondering why nothing happens.
✔ Do this: Call it by name with brackets, for example
greet("Amina").
If something goes wrong
- The console says
Uncaught ReferenceError: x is not defined. - The name was never created or is spelt or capitalised differently. Check the spelling and that the
letorconstline runs before the line that uses it. - The console says
Uncaught SyntaxError: Unexpected token. - Look at the line it names and the line above. A bracket, quotation mark or comma is usually missing or extra.
- I changed a
constand gotTypeError: Assignment to constant variable. - A
constcannot be given a new value. If the value must change, declare it withletinstead. - The page freezes after running my loop.
- The loop probably never ends. Close the tab, then check that the loop condition can become false.
Key terms
- Array
- An ordered list of values kept together in one variable and numbered from zero.
- Object (JavaScript)
- A collection of named values kept together, written with curly brackets.
- Console
- The developer tools panel where a page's messages and errors appear and where you can type JavaScript.
- Developer tools
- A set of panels built into the browser for inspecting a page, running code and seeing errors and network requests.
- String
- A piece of text in a program, written between quotation marks.
- Boolean
- A value that can only be true or false, used to answer yes or no questions in a program.
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.
Complete three lab exercises
Open the JavaScript exercises lab above. Finish at least three exercises, covering a variable, a condition or loop, and a function. For each one, say in your own words what the code does before you press the check button.
Challenge: total the harvest
Without copying, write a script with an array of three objects, each with crop and kilos. Use a loop to print each crop and its kilos, then print the total. Add an if that prints Good harvest when the total is 50 or more. Test by changing the numbers.
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
- JavaScript adds behaviour to a page; console.log shows output while you learn.
- Use const by default and let for values that change; compare with ===.
- if / else if / else choose between outcomes; for and while repeat work.
- Functions take parameters, return results and run only when called.
- Arrays are ordered lists counted from zero; objects hold named properties.
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 basics (MDN Web Docs)
- JavaScript reference (MDN Web Docs)