Type something to search...
Solution to Day 4 of 7 Days of JS

Solution to Day 4 of 7 Days of JS

  • JavaScript
  • Challenge
  • Lautaro Lobo
  • 02 Dec, 2019

So, first the shortest solution:

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

console.log(reverseString('Japan'))

I’ve used 3 methods here: split(), reverse() and join(). The split method turns the string into an array of characters, then I use the reverse method, that reverses (duh) the array, and then I take the array of characters and make it look again like a string.

Then I cracked my head up to make it work with a for loop:

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

console.log(reverseString('Bananas'))

And also implemented this same algorithm as a while loop:

function reverse(string) \{
  let output = '';
  let i = string.length - 1;
  while (i >= 0)\{
    output += string[i];
    i--;
  }
  return output;
}

console.log(reverse('goodbye'))

Do you have any questions? Write a comment!

Cheers!


Related Posts