0

When I write same logic in C programming it reverse the string but in Javascript it is not working, Can somebody help to figure out why? Thanks in advance.

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


console.log(reverse("anil"))
David
  • 208,112
  • 36
  • 198
  • 279
A.kumar
  • 9
  • 1

1 Answers1

4

Strings in JavaScript are immutable.

You can read a character from a position with foo[index] but you can't write to it.

Convert the string to an array of single-character strings with split. Then convert it back to a string (with join) at the end.

function reverse(str) {
  let res = str.split("");
  for (let i = 0; i < str.length / 2; i++) {
    let temp = res[i];
    res[i] = res[res.length - i - 1];
    res[res.length - i - 1] = temp;
  }
  return res.join("");
}


console.log(reverse("anil"))

That said. Arrays have a reverse method, so you don't need to reinvent the wheel.

function reverse(str) {
  let res = str.split("");
  res.reverse();
  return res.join("");
}


console.log(reverse("anil"))
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335