Don't understand for statement in this code

Hi coders,
I saw this snippet function that to reverse a string, but I don’t understand the for statement why are there these arguments? :pensive:
’ ’ ’

function reverseStr(str){
  let newStr = ""
  for (let i = str.length-1; i >= 0; i--){
    newStr += str[i]
   }
   return newStr
}

Regards,
CamCode

1 Like

The for loop has the following syntax:

for ( *statement 1* ;  *statement 2* ;  *statement 3* ) {
  //  *code block to be executed*
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

so statement 1 is ran once at the very start of the for loop, its initiating a variable ‘i’ with the value str.length-1, which is the index of the last letter of the string.

now it runs what’s inside the block, so it adds the last letter of the str to newStr.

statement 3 is then ran, so we subtract 1 from i, giving us the index of the 2nd last letter of the string.

then statement 2 is ran, if it’s true, the loop continues, if it’s false we exit the loop.

so this loop will run until i=0, the index of the first letter of the string.

basically, it counts down from the index of the last letter. each time adding that letter to a new string.

1 Like

The for loop is running from backwards. This means from the last character to the first character. And this way it reverse a string. Hope you understand what I mean.

Very good explanation @M-Michelini

Thanks @M-Michelini and @diana123 for your
explanations.

1 Like

hello,

thanks for your explanation this is really helpfull for me

thanks and regards

1 Like