For..of loops confusion

38 views Asked by At

So I've been writing 'for' loops only with the (let i = 0; i < arr.length; i++) set up until now. This is visually something you can break down and understand so its been logical for me. Now I'm being taught the for..of loop and it's not as easy to directly see whats going on. I understand its just a simpler way to write it in relation to arrays - but I'm wondering if they have designed it to operate as a function with the keywords 'for' 'const' and 'of' or if someone might be able to help me understand how this code is actually operating?

I tried to formulate the question to someone but it seems from their response maybe this is just going to be one of those things you just DO without actually seeing the logic of how its working in itself. As far as I can tell it operates more like a function with parameters?

const clay = [ "Clay", "Clay", "Clay", "Clay" ]
const toFireInKiln = []

for (const i of clay) {
   const mug = `${i} coffee mug`
   toFireInKiln.push(mug)
}



console.log(toFireInKiln)

I can use it as it's meant to be used but I am not understanding the functionality as it runs.

1

There are 1 answers

0
Enigmativity On

I don't know if this C# example helps, but here are two versions of the code - one using foreach and the other using the underlying method calls that make it work.

IEnumerable<string> letters = new[] { "A", "B", "C" };

foreach (string letter in letters)
{
    Console.WriteLine(letter);
}

using (var e = letters.GetEnumerator())
{
    while (e.MoveNext())
    {
        Console.WriteLine(e.Current);
    }
}

The IL (bytecode) that gets generated is pretty much identical for both blocks of code.