-1

function reverse(str) {
  var reversed = '';
  for (let el of str) {
    reversed = el + reversed;
  }
  return reversed;
}
console.log(reverse('baca'));

The out put of this code is acab. but how?

As far as i know when i add a empty string with a value it will create an extra space after that but how it reversed? I have tried 1 day long for under standing reversed = el + reversed; this line but i found that it will be b + ' ' + a + ' ' + c + ' ' + a.

But how it reversed after return ...please help me.

Liam
  • 27,717
  • 28
  • 128
  • 190
sumon
  • 147
  • 1
  • 1
  • 5
  • 1
    Your finding is wrong, note that `reversed` is declared outside the loop and it's reassigned inside the loop. It will be `'b' + ''` then `'a' + 'b'` and so on. To help you debugging you may consider to add `console.info()` to monitor how variables evolve (if not debugging step-by-step...) – Adriano Repetti May 29 '18 at 11:11
  • 1
    You're prepending the string, not appending it, making it seem reversed. – Ben Fortune May 29 '18 at 11:12
  • 4
    I really don't think this is worth 6 downvotes...I mean I'd love to know how people feel this is "not showing research effort is unclear or not useful"? – Liam May 29 '18 at 11:13
  • 3
    At the very least, you should consider this an excellent opportunity to familiarize yourself with the use of a debugger. Using your browser's debugger you can step through the code, line by line, as it executes and observe the runtime behavior and values of the variables. When you do this, is there any specific operation on any specific line of code which, when given the values it has at runtime, produces a result that you don't expect? What was that specific operation? What were the input values to it? What specific result did you expect? Why? – David May 29 '18 at 11:17

1 Answers1

4

It's a loop, think about how the loop is iterating over each character.

Iteration 1: 'b' + '' = 'b'

Iteration 2: 'a' + 'b' = 'ab'

Iteration 3: 'c' + 'ab' = 'cab'

Iteration 4: 'a' + 'cab' = 'acab'

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97