Reverse a String optimize

Tell us what’s happening:
Hi, I got the code to run so there is no problem there; my question is is there anyway to have shorter code that does the same, and not using JS methods. (maybe without declaring a new variable).

Your code so far


function reverseString(str) {
  let newStr = "";
  for (let i = 0; i < str.length; i++){
    newStr = str[i] + newStr;
  }
  return str = newStr;
}

reverseString("hello");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string

Try this

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

reverseString(“hello”);

That’s as optimal as you’ll get it, but what @ymoua17 says is normally the way you’d do it for brevity.

1 Like

Using only the methods covered in the chapters preceding this exercise, here is my proposition.

function reverseString(str) {
	return str == "" ? "" :
		str.slice(-1) + reverseString(str.slice(0, -1));
}

Different solution with recursion and ES6:

const reverseStr = str => !str ? '' : reverseStr(str.substr(1)) + str.charAt(0);
reverseStr("hello");