0

Normally I use loops for incrementing/decrementing, looping through arrays, objects etc.

When doing Javascript Koans, one of the first problems stumped me.

var result = 0;
 for (var i = 0; i <=5; i++) {
 result += i;
}
console.log(result); //15

I am failing to understand why this outputs 15. From looking around I cannot seem to find another question on this specifically--or documentation to enable me to learn further. "+=" is not a valid search term in Google.

Source is here(1st/2nd question): https://github.com/liammclennan/JavaScript-Koans/blob/master/topics/about_operators.js

Thanks!

Jahsa
  • 45
  • 6
  • 1
    Don't say you are new to coding, it is irrelevant. The answer will never be "this code only works if you've been coding for 5 years: x". This site is for asking questions and I assume you are not new to asking questions. – JK. Jan 13 '15 at 00:00
  • 1
    `+=` is one of the [assignment operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators) specifically the [addition assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment) operator – Patrick Evans Jan 13 '15 at 00:00
  • Thank you JK, I will amend it. Patrick thank you for the links those are exactly what I needed to get my head around this. – Jahsa Jan 13 '15 at 00:06
  • I think when someone flags they are new to coding it's a flag for answeres to make an effort to more thoroughly explain any basics involved vs making assumptions about prior knowledge... – Marty Jan 13 '15 at 00:08

1 Answers1

1

Well, let's take this apart step by step: The loop runs 6 times, in each iteration 2 things happen: i gets incremented and the current value of i gets added to result, so

result = 0 + 1 + 2 + 3 + 4 + 5 = 15

in most programming languages, x += y is syntactic sugar (i.e. a shorthand) for x = x + y

mmgross
  • 3,064
  • 1
  • 23
  • 32
  • Ah, it is the += operator I was not properly understanding. This perfectly explains what I was not getting, thank you! – Jahsa Jan 13 '15 at 00:03