0

JS string reversal- how this code works?

function reverseString(print) { let result = ""; for(let char of print) { result = char + result; } return result; } Hi so this code takes in text and reverses it. For example: input: 'Hello, World!' output: '!dlroW ,olleH' but I dont quite understand it, could someone explain how it works? Also do any of you have a way of figuring out how and why a code works? Thanks!

2nd May 2019, 6:54 PM
Evie
Evie - avatar
6 Answers
+ 3
reverseString("Hello"): result = "H" result = "e"+"H" (="eH") result = "l"+"eH" ... result = "o"+"lleH" (="olleH")
2nd May 2019, 6:58 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Hey Aymane Boukrouh and Sergiu Panaite understand his question guys 🙂
2nd May 2019, 7:08 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
+ 1
Initially the result is empty. you add first char from string in result. then you add second one in front of result and so on.
2nd May 2019, 7:00 PM
Sergiu Panaite
Sergiu Panaite - avatar
+ 1
thanks a lot @Aymane Boukrouh!
2nd May 2019, 7:32 PM
Evie
Evie - avatar
0
var str='Hello world'; alert(str.split('').reverse().join(''))
2nd May 2019, 7:00 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
0
// Or var str='Hello world'; for(let i=str.length-1; i>0; i--) document.write(str[i]);
2nd May 2019, 7:02 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar