Object method example

hello campers

i am having issues with the below

const counter = {
  value: 23,
  inc: function(){
  return this.value++}
}
console.log(counter.inc());

the above gives me 23

const counter = {
  value: 23,
  inc: function(){
  return this.value+=1}
}
console.log(counter.inc());

the above gives me 24. i am not understanding why

What happens if you do the console log a second time?

console.log(counter.inc());
console.log(counter.inc());

This might give you a hint as to what is going on.

Or, try putting the ++ in front of this.value instead.

i put the ++ before the this.value and it worked. Why is that please?

Also, calling it twice also gave the right answer on the second calling. Why won’t the first call return the right answer?

i learnt that value++ is equivalent to value+=1. but it is now acting differently in this case. it is really confusing now

++a and a++ these two operators are different. The first one changes the value of a and returns the value. The second one saves the initial value, then increments the value of a and then returns the initial value. So if you just use them for incrementing the value, there would be no difference, as both of the operators do the same in terms of adding 1 to the value, but if you want to use the result of the expression right away you’ll get different results.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.