Is this correct? (While and For loop)

Here is the while loop:

const myArray= ;
let l = 5;
while ( l >=0) {
myArray.push(l);
l–;
}

For loop:

const myArray= ;
for (let l= 5; l>=0 ; l–) {
myArray.push(l);
}

Is this correct?
I’m trying to make sure that my understanding is right before I move on to the next lesson.

Thank you in advanced!

That depends on what you want to do. If your goal was to do the same thing with each loop, then yes. In general, it’s best to use the most specific tool that fits semantically, so for this task, for would be better.

I would say to avoid a single lower case “L” for a variable name. Is is a lowercase “L”? An upper case “I” as in “igloo”? Is it a number “1”? In some fonts they all look the same. A common generic looping variable is a lowercase “i” (then “j”, then “k”) so I assume that you’d used an uppercase by mistake. I think that single letter variable names should be avoided except in simple indexing or in short and simple callback functions where it is clear what they mean. I would agree that this is the former case, but I’d avoid the lowercase “L”.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.