The array and for…of
Section 6: Arrays and building the page with codeLesson 6.1 · ⏱ 9 min
An array is a list in JavaScript between square brackets [ ]. And for (const name of team) goes through its items one by one.
document.createElement("li")makes a new element.li.textContent = …puts the text in it.list.appendChild(li)adds it to the page.
HTML
<h2>My team</h2>
<ul id="list"></ul>
CSS
body { font-family: Tahoma, sans-serif; }
li { font-size: 20px; margin: 6px 0; }
JavaScript
const team = ["Ali", "Mona", "Omar", "Sara"];
const list = document.getElementById("list");
for (const name of team) {
const li = document.createElement("li");
li.textContent = "🤖 " + name;
list.appendChild(li);
}
console.log("Team size:", team.length);
🖥️ The page in Robo Web:

🖥️ The Console in Robo Web:
Team size: 4
📌 Another example: the biggest number in the array
We go through all the marks, and keep the biggest.
HTML
<p>Look at the Console 👇</p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const grades = [70, 95, 60, 88];
let best = grades[0];
for (const g of grades) {
if (g > best) best = g;
}
console.log("Highest mark:", best);
console.log("Number of marks:", grades.length);
🖥️ The page in Robo Web:

🖥️ The Console in Robo Web:
Highest mark: 95 Number of marks: 4
✍️ Practise
Try the example here: copy the code into its tabs, change it, and watch the page change.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
Test yourself
- Add your name to the array.
- Print the first name in the Console:
team[0].
🎯 Challenge yourself
Easy
Print every colour in the colours array.
👀 Show the solution🙈 Hide the solution
HTML
<p>Console 👇</p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const colors = ["Red", "Green", "Blue"];
for (const c of colors) {
console.log(c);
}
🖥️ The page in Robo Web:

🖥️ The Console in Robo Web:
Red Green Blue
Result: three lines.
Medium
Show the fruits in a list on the page.
👀 Show the solution🙈 Hide the solution
HTML
<ul id="list"></ul>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const fruits = ["🍎 Apple", "🍌 Banana", "🍇 Grapes"];
const list = document.getElementById("list");
for (const f of fruits) {
const li = document.createElement("li");
li.textContent = f;
list.appendChild(li);
}
🖥️ The page in Robo Web:

Result: a list of three.
Hard
The sum of the numbers and their average.
👀 Show the solution🙈 Hide the solution
HTML
<p>Console 👇</p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const nums = [4, 8, 15, 13];
let sum = 0;
for (const n of nums) {
sum += n;
}
console.log("Total:", sum);
console.log("Average:", sum / nums.length);
🖥️ The page in Robo Web:

🖥️ The Console in Robo Web:
Total: 40 Average: 10
Result: the sum is 40 and the average is 10.

