How code is written today

INPUT · Slides

Looping without numbers

01 / 06

Minding the number hides the point

For working through an array one item at a time, chapter 2 had you write this.

for (let i = 0; i < fruits.length; i++)

All you want is "one item at a time", yet what is written is all about minding the number i. Start at 0, stop below length, do not forget the i++. Each one easy to get wrong.

There is a way to say "one at a time" without the number appearing at all.

02 / 06

Catch them one at a time with of

Write for (const name of array) and each item goes into that name in turn as it repeats. Nowhere is there a place to write a number.

The two below give exactly the same output. Nothing new became possible; you just gained a way to write the same thing shorter and harder to get wrong.

const fruits = ["apple", "orange"];for (let i = 0; i < fruits.length; i++) {  console.log(fruits[i]);}for (const fruit of fruits) {  console.log(fruit);}

Result

apple
orange
apple
orange

03 / 06

Number mistakes stop happening

While you keep the number yourself, accidents like this happen. Turn one < into a <= and off it goes fetching a number that is not there.

There are two items, so fruits[2] does not exist. Go and fetch it and undefined comes back. Since it does not stop with an error, it is a bug that is hard to notice.

With for...of you never write the number in the first place. The array knows how far to go, so this accident cannot happen.

const fruits = ["apple", "orange"];for (let i = 0; i <= fruits.length; i++) {  console.log(fruits[i]);}

Result

apple
orange
undefined

04 / 06

const is fine for the catching name

The i in a for was raised every lap, so it needed let. But the name you catch with in a for...of is made fresh each lap, so if you do not rewrite it, const is fine.

A different value each time and yet const is all right may look a little odd, but each lap is a separate variable, so nothing goes wrong.

const nums = [3, 5, 8];for (const n of nums) {  console.log(n * 2);}

Result

6
10
16

05 / 06

The difference from forEach is break

If you only do the same thing to every entry, forEach wrote that too. The big difference is whether you can stop partway.

  • for...ofbreak leaves the loop then and there
  • forEach … the handed function is always called to the end

Work that goes "finish the moment it is found" is where for...of steps up.

const nums = [4, 7, 9, 12];for (const n of nums) {  if (n % 3 === 0) {    console.log(n);    break;  }}

Result

9

06 / 06

When you need the number, stay with for

Learning for...of does not make chapter 2's for unnecessary. Think of it like this.

  • work through one at a timefor...of
  • you need the number itself → chapter 2's for (showing no. 1, going from the back)
  • how many laps depends on a conditionwhile

You only gained a tool. Right — let us loop without numbers.