Javascript Reverse a String...why won't my solution decrement?

function reverseString(str) {  
  var buildString = "";  
  var buildArr = [];  
  var strLength = str.length;
  for (var i = strLength -1; i >= 0; i--) {    
    var strLetter = str.charAt(i);    
    buildArr.push(strLetter);       
  }

  for (var j = 0; j < strLength; j++) {
    buildString = buildString + buildArr[j];   
    return buildString;    
  }
var newStr = buildString;
return newStr;
}

reverseString("hello");

Because you have a return statement inside your second for loop, which returns a string ‘buildstring’. On the first iteration it will take first letter of the array ‘o’ and then return buildString. Simply remove the return in the second for loop and it should work

1 Like

0ZeroCool is correct. Also, while your logic is sound in your code, there’s a pretty common quick hack for doing this faster - it uses the string method parse, which turns strings into arrays, then the array method reverse, which does just what it sounds like, then the array method join, which puts the reversed array back together into a string. The whole thing looks like this:

function reverseString(str) {
  return str.split('').reverse().join('');
}

FreeCodeCamp did not teach us that line of code you had just provided. It is definitely simple and is the answer the website provides. Why couldn’t FreeCodeCamp talk about “str.split(’ ‘).reverse().join(’ ');” in their lesson?