Tell us what’s happening:
Describe your issue in detail here.
So i was tasked to reverse a string and this is my code. When i run it it return “undefinedello” which doesnt make any sense. Can someone please tell me whats is wrong with it? Your code so far
let newStr = "";
function reverseString(str) {
for (let i = 0; i < str.length; i++) {
const s = str.length - i;
newStr += str[s];
}
return newStr
}
console.log(reverseString("hello"));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36
Challenge: Basic Algorithm Scripting - Reverse a String
If the string is 5 characters long, then the first time through the loop i will be 0. So what is s going to equal? And what is the last index number for a string that is 5 characters long?
This should be defined inside the function body. Do not use global variables.
The issue in your code is with the index calculation inside the loop.
JavaScript uses zero-based indexing, so the last character of a string with length n is at index n - 1 .
In your code, you’re using str.length - i as the index, but it should be str.length - 1 - i because JavaScript utilizes zero-based indexing, where the first character in a string has an index of 0, and the last character has an index of str.length - 1 . In your code, you’re using str.length - i as the index, but this is incorrect because it skips the last character during iteration. The correct approach is to use str.length - 1 - i as the index.
let newStr = "";
function reverseString(str) {
for (let i = 0; i < str.length; i++) {
const s = str.length - 1 - i;
newStr += str[s];
}
return newStr
}
console.log(reverseString("hello"));