0

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

ngTouthang
  • 61
  • 1
  • 10
  • "*finding the lenght*" - don't "find" it by counting, just access `str.length`! And [don't use `for…in` enumerations on indexed structures!](https://stackoverflow.com/q/500504/1048572) – Bergi Jun 27 '22 at 18:03
  • Just trying to avoid any kind of builtin function or method. – ngTouthang Jun 27 '22 at 19:14
  • It's neither a function nor a method, it's just a basic property of strings. Just like `str[i]` is. But you cannot avoid all builtins, you need something to build your program from! – Bergi Jun 27 '22 at 19:40

2 Answers2

0

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--)
0
  • Maybe there is an easier way to do this, if that what are you going for.
const str = 'Hello World';
const reversed = str .split('').reverse().join('')
console.log(reversed); // dlroW olleH
Ahmed ALABSI
  • 21
  • 1
  • 3