Reverse a String hello

Tell us what’s happening:

Your code so far


function reverseString(str) {
    let arr = str.split('');   
    let newArr = [];
    let len = arr.length;
    for (let i = 0 ; i < len ; i++) {        
        let store = arr.pop();        
        newArr.push(store);        
    }
    return newArr.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/70.0.3538.102 Safari/537.36.

Link to the challenge:

Was really hoping to get a review on this approach of string reverse using array functions.

var reverseString = (str) => {
 let str2=[];
 for(let s of str){
   str2 =  [s,...str2];
 }
  return str2.join("");
}

reverseString("hello");

My alternative solution using ES6.

Or

var reverseString = (str) => {
let str2 = str.split("");
str2.reverse();
return str2.join("");
}
reverseString("hello");

To keep it on just one line

var reverseString = (str) => str.split('').reverse().join('');

reverseString("hello");

Thanks very much for these alternatives Paolo!

You’re welcome Sharon!

It’s overly complicated, I would say, it’s difficult to figure out what’s going on. This is the canonical way to do it, and the most obvious:

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

If you really want to use a loop, there’s no need to use an array, you can just loop backwards through the string and build a new string from that:

function reverseString(str) {
  let reversedStr = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversedStr += str[i];
  }
  return reversedStr;
}

For another solution:

function reverseString(str) {
  return [...str].reduceRight((reversedStr, char) => reversedStr + char, '');
}