Loops, and where your data lives

INPUT · Slides

Putting for, if-else if and arrays together

01 / 06

The culmination of the JS course

Last of all: for × if-else if × arrays. The pattern that sorts every item into three or more groups.

Grades A B C, sizes S M L, three price bands — most real classification has three or more options. Write this and you have graduated from JS basics.

02 / 06

You already know every part

You just put an if-else if inside a for. There is no new syntax at all.

Combining tools you already know explodes what you can do — the most enjoyable thing about programming.

let scores = [95, 75, 40];for (let i = 0; i < scores.length; i++) {  if (scores[i] >= 90) {    console.log("A");  } else if (scores[i] >= 70) {    console.log("B");  } else {    console.log("C");  }}

Result

A
B
C

03 / 06

Counting three ways

Set up three counters and you can count how many are in each rank in a single loop.

Add up, sort, display — the screens of an app are made out of this combination.

let scores = [95, 75, 40, 88];let a = 0;let b = 0;let c = 0;for (let i = 0; i < scores.length; i++) {  if (scores[i] >= 90) {    a = a + 1;  } else if (scores[i] >= 70) {    b = b + 1;  } else {    c = c + 1;  }}console.log(a);console.log(b);console.log(c);

Result

1
2
1

04 / 06

The order you write the conditions matters

An else if is judged top to bottom and stops at the first one that fits. So changing the order of the conditions changes the result.

In the example below >= 70 was written first, so even 95 comes out as "B". Write the strictest condition first — that is the rule.

let scores = [95, 75];for (let i = 0; i < scores.length; i++) {  if (scores[i] >= 70) {    console.log("B");  } else if (scores[i] >= 90) {    console.log("A");  }}

Result

B
B

05 / 06

A final else stops anything slipping through

End with an else and you always catch whatever fitted none of the conditions.

Finish with else if alone and nothing gets shown when an unexpected value turns up. When you find "one line of output is missing", this is often why.

06 / 06

Where to next

You now have all three powers: holding data, deciding, repeating.

Those three are the frame that turns up in every program there is. Whatever new syntax you learn from here, what you are doing stays this same combination.

Next you will build screens with HTML & CSS, and after that combine them with JS to make a page that moves. A to-do app is not far off.