Programming

JavaScript: walk an array with a for loop

Read the items, find the sum and the largest, pick the evens and walk the array backwards.

All lessons · JavaScript lessons: learn from scratch

Walk an array with for

for has three parts: a start, a condition and a step. For an array the counter starts at 0 and grows while it is smaller than length. meyveler[i] is the current item.

let meyveler = ["alma", "armud", "banan", "gilas"];
for (let i = 0; i < meyveler.length; i++) {
  console.log(meyveler[i]);
}
// alma, armud, banan, gilas

Sum, the largest and the evens

The same loop takes a condition. For a sum you add each item. For the largest you start with the first item and compare the rest. An even number is one where % 2 === 0.

let reqemler = [12, 45, 7, 89, 34];
let cem = 0;
let enBoyuk = reqemler[0];
for (let i = 0; i < reqemler.length; i++) {
  cem = cem + reqemler[i];
  if (reqemler[i] > enBoyuk) enBoyuk = reqemler[i];
  if (reqemler[i] % 2 === 0) console.log(reqemler[i]);
}
console.log(cem, enBoyuk);

Backwards and for...of

To go backwards, start at the last index: length - 1, and step down with i--. If you do not need the index, for...of is shorter. Do not write i <= length: the last step is undefined. If you forget i++, the loop never ends.

for (let i = meyveler.length - 1; i >= 0; i--) {
  console.log(meyveler[i]);
}
for (let meyve of meyveler) {
  console.log(meyve);
}

Questions

Why does for start at 0? The first item's index is 0.

Why is the condition i < length? The last index is length - 1. With equal, the missing place is undefined.

How do you know a number is even? If the remainder of dividing by 2 is 0: n % 2 === 0.

When is for...of enough? When you do not need the index. If you need the index or must change an item, write a plain for.

Author: Nibras Code