Reverse a String using for loop

Tell us what’s happening:
I am swapping two characters in for loop but why is it not going as expected, not able to figure out why this solution is not working. Kindly help

Your code so far


function reverseString(str) {
  let n = str.length;
  let temp = '';
  for(let i=0;i<n/2;i++) {
    
    temp = str[i];
    str[i] = str[n-1-i];
    str[n-1-i] = temp;
  }
  return str;
}

reverseString("string");

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0.

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

Strings are immutable. You cannot swap their characters but you can concatenate strings to other strings to form new strings.

1 Like

Thank you @hbar1st :slightly_smiling_face:

What you can do though is use the spread/rest operator ‘...’ to put that string into an array and then you can start swapping characters around.

let strArray = [...str]
1 Like

Yes, I totally forgot about the spread operator :sweat_smile: Thanks for the valuable response @camelcamper

Here’s what I got using a for loop. Keep in mind it’s pretty impractical given the alternative is one line of code:
function reverseString(str) {
let switchArr = […str];
let tempArr = [];
for(let i = 0; i < str.length; i++){
let j = switchArr[i];
tempArr.unshift(j);
}
let finalStr = tempArr.join(’’);
return finalStr;
}

reverseString(“hello”);

1 Like