Reverse a string - can anyone remind me of something?

I redid the algorithm and got it correct; however, I forgot why it’s necessary to add a minus 1 in the `loop`.

1 Like

It’s really hard to answer without looking at code.

because array index starts with 0.

Can you elaborate or provide the code to build context, as generally “minus 1” is added to the loop to decrement the variable value and break out of loop.
Like here

``````
for (let i = 5;  i > 0; i--) {
console.log(i);  // prints i from 5 to 1
}

``````

If i is not decremented it will run the loop infinitely as the second condition never gets false.

Yeah, sorry: I did not want someone who has not done this algorithm see an answer. I’m sure @piedcipher is correct.

`````` let y = '';
for(let i = str.length - 1; i > - 1; i--) {
y += str[i]
};
return y;
};
``````
1 Like

Let’s say string is “Tirth”. So `.length` would return 5 as there are 5 characters but array indices are ranging from `0` to `4`. Hence it’s mandatory to minus 1 from the total length to start iterating from 4.

1 Like

Yes this is true in the case of arrays because of 0 based indexing.

As general I thought you are talking about the the third `i--` part as these are more common in loops.

1 Like

If you want to ask a question about solution code you can blur it using the `[spoiler][/spoiler]` tags.

``````hidden
``````

As long as it is a valid question and invites discussion it is fine.

Or try to come up with example code that isn’t using challenge code but still conveys the idea.

1 Like

nice suggestion @lasjorg!

or you could use collapse section:

Example:

Click me

1. Foo
2. Bar
• Baz
• Qux

Some Code

``````function logSomething(something) {
console.log('Something', something);
}
``````

How to build one? [How to add a collapsible section in markdown. · GitHub]

``````<details>
<summary>Click me</summary>

1. Foo
2. Bar
* Baz
* Qux

### Some Code
function logSomething(something) {
console.log('Something', something);
}
</details>
``````

Thanks. That’s why I didn’t post the code in my first post. Thanks once more.

1 Like

True that. When I think of index, `Array` comes to mind. Won’t forget. Thanks.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.