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!

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 JavaScript Array Iteration Methods Array Manipulation Return a Single Value from an Array with reduce()

Why does return count++ not work here

count ++ is the same as count +1 and count +=1 or am I going crazy today!?

Gremyko Coleman
Gremyko Coleman
9,490 Points

I was thinking the same thing as you, its crazy, you learn something new everyday, now I know to use ++count, if the variable count is not a global variable.

1 Answer

Steven Parker
Steven Parker
224,872 Points

The "++" operator is known as a "post-increment", which means that it returns the current value first, and then increments it.

So when it appears on a line by itself, it does the same thing as the other examples. But when you do something directly with the value (like in a "return") you get a different value.

You didn't show the actual code, but unless "count" is a global, you probably want "count + 1" there.

Doron Geyer
seal-mask
.a{fill-rule:evenodd;}techdegree
Doron Geyer
Full Stack JavaScript Techdegree Student 13,896 Points

Just to demonstrate this visually as that often helps.

let i = 1;
function increment(){
  console.log(i++);
};
increment();
// i = 1
console.log(i);
// i = 2

please correct me if I'm wrong here Steven Parker , but the above snippet basically i is logged as 1 inside the function and after it is logged, it gets incremented. Which is why outside the function when logged again it is shown as 2 ( post increment).

Steven Parker
Steven Parker
224,872 Points

Yes this example effectively illustrates how post-increment works.

And for comparison, if you substitute the pre-‚Äćincrement operator instead, both logged values will be 2:

  console.og(++i);  // PRE-increment operator
karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

hey Steven Parker, but even if count++ is post-increment, it should still show 3 at-least, coz returning the value 0 first and then increment, will make the value still 1 for the next time, but why does it show 0 ?

Steven Parker
Steven Parker
224,872 Points

That's the difference between "pre" and "post". The "pre" operator changes the value now. The "post" operator changes it for next time but returns what is already was this time.