Search code examples
javascriptstringfor-loopconcatenationundefined

javascript undefine keyword prefix with a string


i try to reverse a string by finding the lenght first, using for-loop and den loops throught the range from the lenght to zero and concat it with other variable in order to store it in a reverse order, but i always get undefined prefix to it.

code -

function reverse1(str) {
  let len = 0;
  for (let i in str) {
    len += 1;
  }
  var r = "";
  for (var i = len; i >= 0; i--) {
    r += str[i];
  }
  return r;
}
console.log(reverse1("hello"));

output- undefinedolleh

How to get rid of this undefined keyword which get prefix in the reverse string


Solution

  • You Are assigning i in for loop with string length , it should be start from len-1

    for (var i = len-1; i >= 0; i--)