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>
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Jehyun
  • 21
  • 2

2 Answers2

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;
        }

    };
}
sbking
  • 7,630
  • 24
  • 33
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>
brian d foy
  • 129,424
  • 31
  • 207
  • 592
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339