1

I was trying to reverse a string using a for loop. The approach I took was to iterate backwards through the entire string, get each separate character of a string in a descending order and then concatenate the reversed characters together in a new, reversed string. However, I encountered a small issue - the string did reverse, but 'undefined' was concatenated at the start.

What am I doing wrong and why this is hapenning? Many thanks for help in advance.

Please, see the code snippet and console for details.

const string = "A quick brown fox jumped over the lazy dog.";
let newStr = "";

for (let i = string.length; i >= 0; i--) {
  let char = string[i];
  newStr += char;
}

console.log(newStr);

2
  • 1
    Your i starts at string.length, consider what happens when you try and access string[string.length] from your string Commented Feb 14, 2022 at 11:30
  • 1
    The following makes it simple to reverse. string.split("").reverse().join("") Commented Feb 14, 2022 at 11:37

2 Answers 2

3

Because array starts from 0 and latest element is accessible by length-1 so the array[length] is equal to writing array[999999]

const string = "A quick brown fox jumped over the lazy dog.";
let newStr = "";

for (let i = string.length-1; i >= 0; i--) {
  let char = string[i];
  newStr += char;
}

console.log(newStr);
//alternative way
console.log(string.split('').reverse().join(''));

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

2 Comments

Makes sense, thank you. I actually knew how to get the last element in an array/string, just couldn't put 2 and 2 together.
@superpav cool, I'd also added an alternative way FYI too
0

You should start from string.length - 1 since string[string.length] is trying to refer an element out of bounds of the array, hence, evaluates to undefined

const string = "A quick brown fox jumped over the lazy dog.";
let newStr = "";

for (let i = string.length - 1; i >= 0; i--) {
  let char = string[i];
  newStr += char;
}

console.log(newStr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.