LetMeSOThat4U LetMeSOThat4U - 27 days ago 7
Javascript Question

valueOf function set to always return the same value

This:

% node
> var o = {valueOf: function() { return 5; } };
undefined
> o += 1;
6
> o
6
> o += 1;
7
> o
7


Why is
o
value incremented if
valueOf
always returns 5?

Answer

Starting from the situation where o references the object as seen in the question:

var o = {valueOf: function() { return 5; } };

Then in the expression

o += 1;

what happens is:

  1. The value of o is obtained as a number, via the call to .valueOf()
  2. That value is added to 1, giving 6
  3. That result is assigned to the variable o

Thus the variable o, which once contained a reference to an object, now contains a number.

Comments