Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
8,774 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
210,144 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,842 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
210,144 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