Please help me with this 😥

I wanna make a code which reverses the text

1 Like

Hey there,

So you want your for loop to start at the last letter of 'hello', and loop until it reaches the first letter.

Right now, i is set to string.length, which is 6. Remember that indexing starts at 0, so the index of the 'o' in 'hello' is 5.

Change let i = string.length to let i = string.length - 1

Also remember that the 2nd part of the classic for loop tells the loop to run as long as a certain condition is true. As soon as it becomes false, the for loop stops.

Right now you have i === 0. This means that the loop is stopping as soon as you start it, because you’ve set i to a number greater than 0.

Change i === 0 to i >= 0.

Hope this helps!
Ben

The function does not have any return statement, so it returns undefined. Follow my slightly improved version:

var text = ‘Hello’;
function reverse(str) {
let reversed = ‘’;
for (let i = str.length - 1; i >== 0; i - -) {
reversed = reversed + str[i];
}
return reversed;
};
console.log(reverse(text));
text = ‘What are you doing?’;
console.log(reverse(text));

Output:
olleH
?gniod uoy era tahW

I hope you get it right!

Love, Lawrence

PS. In the case of your code, the output will be undefined.

1 Like

var txt = 'hello';
function reverser(string) {
for (let i = string.length; i === 0; i--) {
console.log(string[i]);
console.log(string);
}
};
console.log(reverser(txt));
The reverser() function is called and txt is used as an argument. txt has a value of 'hello'.
string === 'hello'
i has a value of 'hello'.length, 5.
5 does not equal 0. The loop is never run.
The console.log() this reverser() function call was inside doesn’t have any value returned from the function, so undefined gets logged to the console.

Code Output

Make a classic for loop.
You can make i equal 0. The loop continues if i !== string.length. For the first time through the loop, log string.length - 1 plus i to the console. For the next time, log string.length - 3 plus i to the console. Etc.

How would you rate the quality of this reply?

  • 1
  • 2
  • 3
  • 4
  • 5

0 voters

1 Like