Codiqo

Learn JavaScript · lesson 27 of 60 · about 7 minutes

Looping and Searching Arrays

Welcome visitors back: visit every name with for...of to count how often they've signed, and search arrays with includes and indexOf.

What you'll learn

  • Loop with for...of
  • Check membership with includes()
  • Find positions with indexOf()

Welcome back

Some visitors sign more than once. A for...of loop visits each name in guests in turn, so the page can count how many of them are the visitor's and say welcome back to anyone who has been here before.

for...of

for (const item of arr) gives you each item in turn, so you don't need to manage an index.

Totalling with for...of

const prices = [3, 7, 2];
let total = 0;
for (const p of prices) {
  total += p;
}
console.log(total);

Output

12

Step through it: counting one name

const guests = ["Ada", "Bo", "Ada"];
let visits = 0;
for (const name of guests) {
  if (name === "Ada") {
    visits++;
  }
}
console.log(visits);

Output

2

Searching

arr.includes(x) returns true or false. arr.indexOf(x) returns the position, or -1 if it isn't there.

includes and indexOf

const langs = ["python", "javascript"];
console.log(langs.includes("python"));
console.log(langs.indexOf("javascript"));
console.log(langs.indexOf("rust"));

Output

true
1
-1

Tip

Need the index too? Use for (const [i, item] of arr.entries()).

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.