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 trialDwayne Bynum
10,408 PointsWhy does return count++ not work here
count ++ is the same as count +1 and count +=1 or am I going crazy today!?
1 Answer
Steven Parker
231,184 PointsThe "++" 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
Full Stack JavaScript Techdegree Student 13,897 PointsJust 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
231,184 PointsYes 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
Web Development Techdegree Graduate 18,135 Pointshey 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
231,184 PointsThat'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.
Gremyko Coleman
9,756 PointsGremyko Coleman
9,756 PointsI 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.