1

I think the code below should display 4, why does it produce 3?

function arithFunc() { var n = 0; return { plusOP: function() { return n++; }, minusOP: function() { return n--; } }; } var aTest = arithFunc(), bTest = arithFunc(); document.getElementById("demo").innerHTML = aTest.plusOP(); document.getElementById("demo").innerHTML = aTest.plusOP(); document.getElementById("demo").innerHTML = bTest.minusOP(); document.getElementById("demo").innerHTML = aTest.plusOP(); document.getElementById("demo").innerHTML = bTest.minusOP(); document.getElementById("demo").innerHTML = aTest.plusOP();
<p id="demo"></p>

2
  • First thing to do is correct your code formatting so that we can understand easily. Commented Jun 28, 2017 at 15:55
  • It might help a lot to fill an array with all the result values and look at all of them, not only the last. Commented Jun 28, 2017 at 15:58

2 Answers 2

5

You are using postfix increment and decrement operators. These are calculated after the value is returned. For example:

var n = 0; console.log(n++); // 0 console.log(n); // 1 

Try using prefix operators instead:

var n = 0; console.log(++n); // 1 console.log(n); // 1 

Your code would then look like:

function arithFunc() { var n = 0; return { plusOP: function() { return ++n; }, minusOP: function() { return --n; } }; } 
Sign up to request clarification or add additional context in comments.

4 Comments

I suggest showing console.log(++n); behavior as well
@PatrickBarr Good point, added.
I understand. Thank you~
@Jehyun Can you mark this answer as accepted?
3

You are over-complicating things: n++ evaluates to the value of n, and then increments n.

aTest and bTest have their own private copies of n, so all those bTest.minusOP invocations are irrelevant to the final contents of p#demo which only gets the value returned by the last plusOP.

n starts out as zero. The first return n++ returns 0 and increments n to 1. The next return n++ returns 1 and increments it to 2 etc etc

function arithFunc() { var n = 0; return { plusOP: function() { return n++; }, minusOP: function() { return n--; } }; } var aTest = arithFunc(), bTest = arithFunc(); document.getElementById("demo").innerHTML += " " + aTest.plusOP(); document.getElementById("demo").innerHTML += " " + aTest.plusOP(); document.getElementById("demo").innerHTML += " " + bTest.minusOP(); document.getElementById("demo").innerHTML += " " + aTest.plusOP(); document.getElementById("demo").innerHTML += " " + bTest.minusOP(); document.getElementById("demo").innerHTML += " " + aTest.plusOP();
<p id="demo"></p>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.