Need help understanding the "for of" loop

In the “Find the Longest Word in a String” section of Basic JavaScript Algorithms, Ramón used a for of loop. I was curious, so I tried to get the same result by looping through the “words” variable with a regular for loop, but I kept getting 9 as the result instead of 6.

Does anybody know why that is? I tried working out the logic in my head, and I don’t see why I’m getting a count 3 characters higher than it should be.

1 Like

Hey Jacob!

I hope I didn’t mislead you with the for of loop! Could you please share the code with us?

Conceptually, the two loops below do the same thing:

const arr = [1, 2, 3];

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

for (let number of arr) {
1 Like

Thanks! I lost my other code, but I’ll look this over and try to get my brain to logic it out.

1 Like

Hi @Jacobra_the_Great and @hola_soy_milk

If Ramón allow me to expand his example… lol. You might understand better what are you doing there with the same example but with a bit more prose and longer and more specific names:

const array = [‘a’, ‘b’, ‘c’];

for (let index = 0; index < array.length; index++) {

console.log(index + ’ ’ + array[index]);

console.log("After this line the for…of loop starts: ");

for (let arrayElement of arr) {

You can copy and paste that code directly into browser’s Console and check the result :slightly_smiling_face: :slightly_smiling_face:

**this is what my Console says:

0 a
1 b
2 c
After this line the for…of loop starts:

I hope it helps! I bet you’ll get anyway. Sometimes its just our brain needs some time to get it because we are trying to memorize too much information in a short time.
Happy coding all!!


Thank you so much, @carlost2672543! Well put.

1 Like

Thanks a ton! I’ll give it a look.

1 Like