JavaScript reverse loop.

The task was to access the chores in the chores array and use a reverse loop to add them to the priority array in reverse order.

I was thinking that the left side of the image would be correct.

My thinking pattern is like this: Okay start from the last value of the chores array and go until the "chores.length" and give that to me in priority. But apparently, I was wrong and can you explain why?

I am a self-taught + mini BootCamp (once session per week) developer, so open to any advice. For example, I am not even sure if my perspective is correct. Any advice would be appreciated. Thanks in advance!

Also, I feel like I am learning it quite slower than my fellows in the same program, as I am working 40 hours per week as an SAP consultant. Quite challenging to find the mental energy to fully concentrate on coding after exhausting hours.

https://preview.redd.it/u3upy1qy3ic81.png?width=1823&format=png&auto=webp&s=26d39f16fadd3a48c95efb4d6a52d69be496a253

5 comments · 100% upvoted · other discussions

comments

liukang2014
  • you started from 2, means you’re assuming the array will always have 3 elements (0,1,2). If you want to start from the last element, you should use array.length - 1

  • to make a reserve loop, you would need to browse from the last element (2) to the first element (0): i starts from 2, then 1, then 0. So the loop will be: i starts from 2 (or array.length - 1) loop until i = 0 decrease i by 1 every loop

Btw use the { and }. Try to avoid single line code. It saves you some milliseconds, but makes the code less readable.

Feel free to ask if you’re not clear

ProfessorMeatHammer

You're letting your for loop run while i is less then chores.length (3) then decrementing i. This creates an infinite loop because i will always be less than 3.

Try this:

for (let i = chores.length - 1; i >= 0; i--) {

    priority.push(chores[i]);

}

Sorry for the crappy formatting, I'm on mobile.

ataisim [OP]

Thanks a lot for the explanation and advice!

So would this be also right (assuming that the arrays are listed):

for (var i = 2; i = 0; i--); {

priority.push(chores[i])

}

Can you see the immediate reaction to your feedback? :)

ataisim [OP]

Thanks a lot!!