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!
6 Answers
+ 3
reverseString("Hello"):
result = "H"
result = "e"+"H" (="eH")
result = "l"+"eH"
...
result = "o"+"lleH" (="olleH")
+ 2
Hey Aymane Boukrouh and Sergiu Panaite understand his question guys đ
+ 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.
+ 1
thanks a lot @Aymane Boukrouh!
0
var str='Hello world';
alert(str.split('').reverse().join(''))
0
// Or
var str='Hello world';
for(let i=str.length-1; i>0; i--)
document.write(str[i]);