0

got a very quick question to y'all as I'm relatively new to JavaScript. This task is actually from the freeCodeCamp course and it's about reversing a string as shown in the title. The question is, why do we include the -1 integer in the str.length line when we can just use the i-- to decrement the string count while reversing the actual string?

It kind of reminds me of what we do when using recursion for counting a set of numbers like (n-1), (n-2), (n-3) etc. Is it the same pattern going on? Or is it because of array's index counting since 0 is the first letter and not 1. Or something else? Thanks :)

function reverseString(str) {
  for (var reversedStr = "", i = str.length - 1; i >= 0; i--) {
    reversedStr += str[i];  
  }   
  return reversedStr;
}
derpirscher
  • 14,418
  • 3
  • 18
  • 35
Martin
  • 1
  • 1

2 Answers2

1

The i = str.length -1 sets the first index for i to look at. As strings and arrays are 0-indexed in most languages, valid indexes go from 0 to length -1 and str[length] would actually be after the last character of the string.

Furthermore i = str.length - 1 is only done once before the first iteration of the loop starts. i-- is done on every iteration of the loop, but at the end of the current iteration.

derpirscher
  • 14,418
  • 3
  • 18
  • 35
0

Length count is started from 1 and index count is started from 0. For "lorem"(let str="lorem") , its length is 5 and but the index of its last character is 4. So if we donot subtract -1 from str.length , in first iteration we will end up with str[5] , which donot exist and will return undefined . Its all counting from 0 vs counting from 1.

lorem1213
  • 433
  • 4
  • 11
  • 1
    Thank you! That lorem example made it clear for me. Since the loop continues to iterate until it reaches its desired statement, it makes sense. Thanks! – Martin Aug 29 '21 at 18:54