0

I am trying to reverse a string but I will get a value as follows when i console.log in chrome console:

function reverseString(str) {
  let newString = "";
  for (let i = str.length; i + 1 > 0; i--) {
    newString = newString + str[i];
  }
  return (newString);
}

console.log(reverseString("hello there"));

Why is there undefined in front of the reverse string?

0

1 Answer 1

1

You start at an i of str.length. On the first iteration, str[i] resolves to str[str.length], but strings are zero-indexed, not one-indexed, so that will always be undefined. Start at str.length - 1 instead:

function reverseString(str) {
  let newString = "";
  for (let i = str.length - 1; i + 1 > 0; i--) {
    newString = newString + str[i];
  }
  return (newString);
}
console.log(reverseString("hello there"));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.