JS Code Explanation: Can anyone explain the logic?

Tell us what’s happening:
So, I was completely stumped by this question and decided to break my rules and go ahead and look for a hint, afterwards I got the right answer, but I still don’t understand why the hints worked, of course since this is a passing solution, I wrapped it in a Spoiler tag.

So, my main question is why does this code work? Can anyone give me a full explanation? Thanks :grinning_face_with_smiling_eyes:

Note:
If you fear spoilers for the rest, feel free to DM me.

var ourArray = [];

for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}

// Setup
var myArray = [];

// Only change code below this line.

for (var i = 1; i < 10; i += 2) {
myArray.push(i);
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.56.

Challenge: Iterate Odd Numbers With a For Loop

Link to the challenge:

i += 2

This is the secret sauce. Can you see why?

@ArielLeslie ,

Well not really but I have a theory, I think it has something to do with the previous statements starting with 0. The altered version of the first for loop starts with 1 therefore 1+2=3 and 3+2=5, and so on?

I still don’t feel so confident so if anyone can give me extra tips and tricks it would be greatly appreciated.

Let’s talk about the anatomy of the for loop.

for(part one; part two; part three){
    loop body
}

“part one” is executed once, before the the loop body ever executes.
The variable i is created and initialized to 1.

“part two” is an expression that is checked before every iteration of the loop body. If it is truthy, the loop body executes. If it is falsy, the loop is done.
The loop stops as soon as i is greater than or equal to 10.

“part three” executes after each iteration of the loop body.
After every iteration, i is increased by 2.

Thanks so much @ArielLeslie ! I can’t believe the answer was right in front of my face LOLOL :grinning_face_with_smiling_eyes:

Thus is the life of a developer I suppose…

Best,
Cy499_Studios

I’m glad I could help. Happy coding!

1 Like

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