Search code examples
javascriptobjectevent-loopcoercionvalue-of

Order of operations when valueOf is called


Right now I'm reading through You Don't Know JS Types & Grammar Ch 4 where I came across this example on coercion. https://repl.it/D7w2

var i = 2;

Number.prototype.valueOf = function() {
    console.log("called"); //this logs twice
    return i++;
};

var a = new Number( 42 );

if (a == 2 && a == 3) {
    console.log( "Yep, this happened." ); //this is logged
}

I don't get why things aren't off by one. Since var i starts out at 2, when it hits a == 2 shouldn't 3 be returned and then shouldn't 4 be returned when a == 3 is run?


Solution

  • No, because you used post-increment. That returns the old value of the variable from before it's incremented.

    If you use pre-increment ++i then it increments the variable and returns the new value.

    var i = 2;
    
    Number.prototype.valueOf = function() {
        console.log("called"); //this logs twice
        return ++i;
    };
    
    var a = new Number( 42 );
    
    if (a == 2 && a == 3) {
        console.log( "Yep, this happened." ); //this is logged
    }