Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Increment Operator (JavaScript)

You can also increment the counter using the ++ operator like this:

for (var i = 0; i < 10; i++) { // do something in here }

Mr. McFarland says this ^

The increment operator increments (adds one to) its operand and returns a value.

If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.

but MDN says this ^

If its going to return a value before incrementing why should we use ++ instead of +=?

1 Answer

Steven Parker
Steven Parker
229,967 Points

There's no advantage to either method in this situation. The "for" loop does not use the return value, so the only purpose is the increment the counter; and both methods do this.

The reason to be aware of the behavior is for situations like this:

var step = 4;
var test = step++;
// at this point, "test" is 4 but "step" is 5

Steven Parker thank you for the info!