Loops, and where your data lives

INPUT · Slides

Putting for, if and arrays together

01 / 07

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 / 07

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 / 07

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 / 07

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 / 07

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

06 / 07

Checking whether anything matches at all

Besides counting and gathering, sometimes you just want to know whether at least one exists. Keep a boolean variable and flip it to true when you find one.

It does not matter how many there are — the moment one turns up, the answer is settled.

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

Result

true

07 / 07

Splitting into two groups with else

Add an else to the if and you can sort items into matches and non-matches at the same time, into two separate arrays.

That is the shape behind splitting a class into those who passed a test and those who did not.

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

Result

[80, 92, 60]
[45]