Basic Algorithm Scripting: Reverse a String (Question on my result))

Hello!
I was wondering if anyone could explain why my output is
o
l
l
e
h

instead of “olleH”. Is the code indenting everytime after it outputs? If it is what is causing it? I’m not really sure why that is. Thanks!

Your code so far


function reverseString(str) {
var newArray =[]; //empty array
var stringLength = str.length; //string length of 5
var newStr ="";

console.log(stringLength);

for(let i=0; i< stringLength; i++){
  newStr = str[str.length-i-1];
  console.log(newStr);
}
return newArray;
}
reverseString("hello");

Your browser information:

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

Challenge: Reverse a String

Link to the challenge:

Well, the CONSOLE returns that because you have a console.log() inside the for loop, that will make it to run again and again until the loop is done. If you actually console.log(); your function, it will return an empty array [ ]. Try it out: console.log(reverseString("hello"));.

Your function doesn’t really return anything, because at the end of the function, you are returning newArray which is an empty string and is not modified in any way

1 Like

Oh wow how careless of me!! Thank you so much!

1 Like

Glad I helped… Now you can go on and try to solve it. Good Luck on it, and Happy Coding!! :slight_smile:

1 Like