-1

Learning JavaScript and doing some questions. I am trying to reverse a given string and I don't know why my logic is wrong as running through the debugger it looks like it's doing the swapping as intended.

Any help is really appreciated, I know it's simple but that means I'm missing something important.

function reverse(s) {
  let i = 0;
  let j = s.length - 1;

  while (i < j) {
    let temp = s[j];
    s[j] = s[i];
    s[i] = temp;
    i++;
    j--;
  }
  return s;
}

console.log(reverse("hello"));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
mangokitty
  • 1,759
  • 3
  • 12
  • 17
  • I would just loop backwards through the original string and concatenate those characters onto a new string, then return it. `function reverse(s) { let j = s.length - 1; let r = '' while (j >= 0) { r += s[j]; j--; } return r; } console.log(reverse("hello"));` – JSONaLeo Oct 10 '19 at 14:33
  • 1
    javascript strings are immutable you can refer to this link to better explanation. https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – Nicollas Braga Oct 10 '19 at 14:35

2 Answers2

0

Since strings are immutable, you can split the string with empty string to make an array and join them before returning:

function reverse(s) {
  s = s.split('');  // split here
  let i = 0;
  let j = s.length - 1;

  while (i < j) {
    let temp = s[j];
    s[j] = s[i];
    s[i] = temp;
    i++;
    j--;
  }
  return s.join(''); // join and return
}

console.log(reverse("hello"));
Mamun
  • 66,969
  • 9
  • 47
  • 59
-2

  function reverse(word) {
      let wordArray = word.split('');
      wordArray.reverse();
      return wordArray.join('');
   }
   console.log(reverse("hello"));
Kostadin Terziev
  • 516
  • 6
  • 15
  • While nice, this doesn't really answer OPs question at all as to why their code was returning the original string. – Drew Reese Oct 10 '19 at 14:35