Increment operators

Get help with Code for Teens
matermultorum
Posts: 3
Joined: Tue May 15, 2018 12:31 pm

Increment operators

Post by matermultorum » Tue May 15, 2018 12:41 pm

I noticed that the following yield different results. After a google search I learned( I think) that counter++; ENTER gives the result before adding 1 and the next time counter is used it will have a value of 1. I wasn't going to ask about this yet as I will probably learn how to use it as the chapter progresses. I also read that ++counter; will yield the increased amount and it will still be that value when used the next time.



let counter=0;
counter=counter+1;
1

counter=0;
counter++;
0



Kendall

JeremyMoritz
Site Admin
Posts: 18
Joined: Mon May 14, 2018 10:19 pm
Location: Kansas
Contact:

Re: Increment operators

Post by JeremyMoritz » Tue May 15, 2018 6:57 pm

Good observation, Kendall!

You are exactly correct that the immediate return value of

Code: Select all

myVar++
is the value BEFORE it's been incremented, but the effect on the variable itself is to increment it by one. I didn't mention

Code: Select all

++myVar
because it is rarely needed in well-formed code.

And good for you for looking that up in Google too! That is one of the most common practices of professional developers!
Jeremy Moritz
Author of Code for Teens
www.CodeForTeens.com

Post Reply