Understanding for loops

I thought I got the hang of the for loops until I came across this. I don`t think I understand what these loops exactly do. Please help.

for (let i = arr.length; i >= 0; i--) {
      arr[i] = arr[i - 1];

 for (let i = 1; i < arr.length; i++) {
      arr[i - 1] = arr[i];

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

The first one sets i to the length of the array arr, stops when your i is < 0 and substracts 1 to i each iteration of your loop.

so if you have arr = ['peach', 'banana']; arr will have length = 2, so at the beginning of your loop i = 2.

The second one, sets your i to 1, will stop when your i is >= than the length of your arr array and adds 1 to i each iteration.

was this your qeustion?

1 Like

A good way to understand what a piece of code does it’s to visualise the output. A simple way to do this is to print the result of each iteration to the console, a more advanced way to do this is using a debugger tool - such as the tool included with visual studio code

1 Like
for (let i = arr.length; i >= 0; i--) { 
// i == number of items in []
// start counting from i
// do something while i >= 0
// let i = i - 1 after each loop
      arr[i] = arr[i - 1];
      // to index i of arr, assign whatever is at index i - 1

 for (let i = 1; i < arr.length; i++) {
      arr[i - 1] = arr[i];
1 Like

Yes, thank you! I had to read through it a couple of times, but I think I got it. Thank you!

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