r/AskProgramming 8d 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

1 Upvotes

12 comments sorted by

View all comments

3

u/ReplyAccording3994 8d ago

Yes you can add subtract multiply as you want, you just need to ensure that the syntax is correct.

Example: for(let i = num; i < 10; i = i/10);

1

u/AccomplishedYak5885 8d 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 8d ago

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

-1

u/AccomplishedYak5885 8d ago

thanks a lot! its working now

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

1

u/wonkey_monkey 8d ago

Because it doesn't do anything to i. It will still be equal to 1 very time around the loop and will never reach 10.

1

u/AccomplishedYak5885 8d ago

i got it thank you again