I am familiar with reversing strings using split,reverse,join, and reverse for loops but I don’t understand how exactly does this for…of loop reverse the string? Can someone explain. I did change reversed = reversed + char and it prints the normal string but I don’t understand how does it reverse a string.
function reverse(str){
let reversed = "";
for(let char of str){
reversed = char + reversed;
}
return reversed;
}
char will be each letter of the str, so you are “adding” each char to the previous chars (reversed).
const str = 'Danilo';
let reversed = '';
for (let char of str) {
// char will be D, a, n, i, l, o
//in the first interaction the reversed will be D, then will be a + D = aD, then n + aD = naD and so on
reversed = char + reversed;
}