Loops, and where your data lives

INPUT · Slides

Putting for, if-else and arrays together

01 / 06

Splitting every item two ways

Last time you handled only the items that matched a condition.

This time you will use if-else to send every single item one way or the other. Pass and fail, even and odd, in stock and sold out — the basic form of sorting things into groups.

02 / 06

if-else inside a for

Every lap, the item goes through exactly one of the if side or the else side.

So the number of output lines matches the number of items. Picture it as "give everybody a verdict".

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

Result

fail
pass
pass

03 / 06

Show the item and the verdict together

Join the item value onto the verdict and you can make output like a report sheet.

Making it clear whose result it is is basic to putting anything on screen.

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

Result

45 pts: fail
80 pts: pass

04 / 06

Send them into two arrays

Set up two empty arrays and push into one on the if side and the other on the else side, and you have sorted the data.

The way your inbox and your spam folder get sorted works on the same principle.

let nums = [3, 8, 5, 2];let even = [];let odd = [];for (let i = 0; i < nums.length; i++) {  if (nums[i] % 2 === 0) {    even.push(nums[i]);  } else {    odd.push(nums[i]);  }}console.log(even);console.log(odd);

Result

[8, 2]
[3, 5]

05 / 06

Make the containers outside the loop

Always set the arrays and counters you sort into up outside the loop.

Make them inside and they go back to empty every lap, leaving only the last entry. When you find "somehow only one thing is in there", suspect this first.

06 / 06

Count both sides and check

Once you have sorted them, it is worth checking whether the two added together come to the original count.

An if-else always goes down exactly one side, so the sum has to match the number of items. If it does not, either the condition or where you put the push is wrong.

Having a way of marking your own work like this is a very useful habit in programming.

let nums = [3, 8, 5, 2];let even = [];let odd = [];for (let i = 0; i < nums.length; i++) {  if (nums[i] % 2 === 0) {    even.push(nums[i]);  } else {    odd.push(nums[i]);  }}console.log(even.length + odd.length);console.log(nums.length);

Result

4
4