Reverse a string help - position of return statment?

Tell us what’s happening:
So I just completed the reverse a string challenge but despite getting it right, I was surprised that I got it right and confused as to how the position of the return statement affected the result. From the code below, if I placed the return statement inside of the loop, it would only return the last letter from the inputted string but if the return statement was declared outside of the loop, it would return the full reversed string. Any explanation or a link to a relevant lesson would be appreciated.

  **Your code so far**

function reverseString(str) {
  const splitString = str.split("");
  let reversedArr = [];
  for (let i = splitString.length - 1; i >= 0; i--)  {
    reversedArr.push(splitString[i]);
  }
  return reversedArr.join("");
}

reverseString("hello");
  **Your browser information:**

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

Challenge: Reverse a String

Link to the challenge:

Here, The variable passed to the function needs to be written correctly and If you leave return in the loop, it is not necessary because it will return a lot of results after each loop.:
let reversedArr = ;

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

reversedArr.push(str[i]);

}

return reversedArr.join("");

Here’s the first lesson where return is introduced. As it says:

You can use a return statement to send a value back out of a function.

So if you had your return statement inside your for loop, it would exit the function after the first iteration.

let reversedArr = [];
for (let i = splitString.length - 1; i >= 0; i--)  {
  reversedArr.push(splitString[i]);
  return reversedArr.join("");
}

If this code is what you had before, then with str being “hello”, it would enter the first loop iteration and push “o” to reversedArr, then immediately exit the function returning “o”.

let reversedArr = [];
for (let i = splitString.length - 1; i >= 0; i--)  {
  reversedArr.push(splitString[i]);
}
return reversedArr.join("");

However with this, it would complete all the iterations of the loop so that reversedArr contains ["o", "l", "l", "e", "h"] and then exit the function returning “olleh”.

Ah I see now. Thanks so much for the explanation

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