I++; vs i += 1;


guys, so I’ve been doing code combat for the last 1 week, intensively, and i came back to the first world to test my skills at Kithgard Mastery a level i couldn’t complete before. And i’ve spent some time trying to understand why my code doesn’t work, but finally, solved it with a very small change, though i don’t understand why one version worked and the other failed, i thought they work the same way;

(this will be excerpts of code)
i had an array of enemies in a variable

var enemies = ["Draff","Smerk"];

I’ve incremented that array with the same index as i incremented the while loop

while (i < 2){

i’ve done this many times before and it worked, but in this level it didn’t,
in the end i changed the `



i += 1;

and magically it worked, does anyone know why?


Well, something else must be wrong, because while there are differences, they shouldn’t matter to your code.

i++ is a postfix increment, basically it first returns the variable value, then increments the variable.
i += n is an addition assignment, basically adds the values somehow and assigns it to the first variable

In both cases you are just adding 1, but doing nothing else with the return value, so it should work.

Basically what would happen if you tested these things out in the console:

var i = 0
i++ // 0
i  // 1

// using +=
i = 0
i += 1   // 1
i += '2' // '12'

// there's also the prefix increment, it's like the postfix increment,
// but it first assigns the value to the variable, then returns the value
i = 0
++i // 1
i   // 1 


Couldn’t expect a better answer, thanks fro your time trotod!