Search code examples
javascriptdata-structuresarray-algorithms

string is not returning correct reverse string in javascript


I am trying to reverse the string using following function but it doesn't return correct string. as below i tried with 'devesh' it gives 'hseesh'

var reverseString = function(s) {
    let j = 0
    for(let i=s.length-1; i>=0; i--){
        s[j++] = s[i]
    }
    return s
};

console.log(reverseString(['d', 'e', 'v', 'e', 's', 'h']))
// ['h', 's', 'e', 'v', 'e', 'd']`enter code here`

Solution

  • It's not working because you're overwriting the s inside the for loop,

    instead, create an empty one and fill it :

    var reverseString = function(s) {
      let j = 0;
      let newS = [];
    
      for (let i = s.length - 1; i >= 0; i--) {
        newS[j++] = s[i]
      }
      return newS;
    };
    
    console.log(reverseString(['d', 'e', 'v', 'e', 's', 'h']))