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


Tadjiev Codes
Tadjiev Codes
9,626 Points

How ++ works the irksome parts?????

  1. What output will the following JavaScript code produce? var num1 = 12; var num2 = 21;
    var total = ++num1; //so here total and num1 becomes 13 as we did a pre incrmenting? total = total + num2++; //is it too late for num2 to get incremented? document.write("Total = " + total + "<br>");

a. Total = 22 b. Total = 33 c. Total = 34 (correct) d. Total = 35

1 Answer

Yes, let's go through it step by step.

You start with two variables:

var num1 = 12
var num2 = 21

then you do

var total = ++num1

in this step, first (because ++ is before the variable) you increment num1 by 1, and then you store it to the variable total.

The result is now total = 13 and num1 is also 13.

then you do

total = total + num2++

here you set total equal to itself plus num2, and after that you increase num2 by 1.

the end result will be

console.log(total) // 34
console.log(num2) // 22
console.log(num1) // 13

++ (as well as --) will always increment (decrement for --), but the order in which it does so matters, depending on if you put it in front of or behind the variable.

Tadjiev Codes
Tadjiev Codes
9,626 Points

You made 22 instead of 21 other than that, your explanation is perfect))) total = total + num2++

So here its too late for total to benefit from num2++ as it's after the variable.

Plus, How do you mark the code in the question or answer? Thanks a lot)

Yes sorry, the original var2 was supposed to be 21, I will edit it

Yes, you are correct in your assessment.

You can surround your code with 3 backticks for code blocks `.

Have the three backticks above and below your code, on new lines.