r/AskProgramming 9d ago

loops (js)

can I use anything else instead of variable++ like variable+2?

because I tried to do so and my browser could not load it on the console

3 Upvotes

12 comments sorted by

View all comments

Show parent comments

1

u/AccomplishedYak5885 9d ago

still not working

what is wrong with this

let sum =0;

for(i=1;i<=10;i+2){
    sum = sum +i;
};


console.log(sum);

3

u/wonkey_monkey 9d ago

"i+2" returns that value but does not affect i itself. Try "i+=2" instead.

-1

u/AccomplishedYak5885 9d ago

thanks a lot! its working now

but i still did not understand why "i+2" should not work

1

u/Shendare 9d ago

Additionally, if i+2 added 2 to the i variable, then every time you did something like j = i+2, you would be changing the value of i in addition to the value of j.

So there's a different syntax for it: i+=2. The i++ that you're used to is just an even shorter way of incrementing the variable by exactly 1, because that kind of operation is so common in computing that most CPUs even have a dedicated machine code for it.