Needing Help with Reversing a String

Can anyone explain why my the codes output “H” if I did not add the plus sing?
e.g. reversedStr = str[i];
Here the ‘reversedStr’ itself is empty

function reverseString(str) {
 for (var reversedStr = "", i = str.length - 1; i >= 0; i--) {
 reversedStr += str[i];
 return reversedStr;

The code outputs “H” when reversedStr = str[i] because each loop reassigns the value of reversedStr. The last value assigned is “H”.

1 Like

var resersedStr = ‘’ ";

reversedStr = reversedStr + str[i]; // how each loop reassigns the value by concatenating ‘reversedStr’ variable with ‘str[i]’ ?

The + symbol is not just for addition, it also concatenates strings.
Each loop takes the current value of reversedStr and concatenates the value of str[i].


You missed one. It also casts a string into a Number.

1 Like