Loops, and where your data lives

INPUT · Slides

Putting for, if and arrays together

01 / 05

Three tools in hand

Variables, if, for, arrays — you have the full set of tools.

This time you will put an if inside a for and build "handle only the items that match". Searching, narrowing down, adding up — this is the pattern at the heart of an app.

02 / 05

Put the if inside the for

It looks like this. The { } become doubled up, so the knack is to keep it readable with indentation.

Every lap takes out scores[i] and the if judges it there and then.

let scores = [45, 80, 92, 60];for (let i = 0; i < scores.length; i++) {  if (scores[i] >= 80) {    console.log(scores[i]);  }}

Result

80
92

03 / 05

Count the items that match

When you want to know "how many", set a variable for counting up outside and add one to it inside the if.

A cousin of the "piling variable" pattern for totals.

let scores = [45, 80, 92, 60];let count = 0;for (let i = 0; i < scores.length; i++) {  if (scores[i] >= 80) {    count = count + 1;  }}console.log(count);

Result

2

04 / 05

Gather up only the matches

Push into an empty array and you get a new array of just the items that match.

That is "narrowing down", or filtering. The "show me only things under 3000" on a shopping site works this way.

let prices = [1200, 4500, 2800];let cheap = [];for (let i = 0; i < prices.length; i++) {  if (prices[i] <= 3000) {    cheap.push(prices[i]);  }}console.log(cheap);

Result

[1200, 2800]

05 / 05

The same with text items

Not only numbers — you can pick out of an array of text by a condition too.

Search, count, gather: you will write all three in the questions coming up.

let animals = ["cat", "dog", "cat", "rabbit"];for (let i = 0; i < animals.length; i++) {  if (animals[i] === "cat") {    console.log("cat found at " + i);  }}

Result

cat found at 0
cat found at 2