gstackoverflow gstackoverflow - 8 days ago 5
Javascript Question

console.log outputs 'function <valueOf result> ' instead of '<valueOf result>'

I am reading the javascript manual and I have wtote following code:

//sum
function sum(arg1) {
var sum = arg1;

function f(arg2) {
sum += arg2;
return f;
};

f.valueOf = function () {
return sum;
};

f.toString = function () {
return sum;
};

return f;
}


and I execute it like this:

console.log(sum(1)(2)(3)(4));


According the manual
console.log
should output the result of
valueOf
function

but it output

function 10


please explain this behaviour.

Answer

According the manual console.log should output the result of valueOf function

I don't know what "manual" you're talking about, but in general, console.log doesn't call valueOf on what you output. The implementations of console.log vary from JavaScript engine to JavaScript engine, but in general they try to give you more useful information than calling valueOf would.

If you want to trigger valueOf, you'll need to do that intentionally, for instance:

console.log(sum(1)(2)(3)(4).valueOf());
// ------------------------^^^^^^^^^^

or (since your function is designed to produce a number):

console.log(+sum(1)(2)(3)(4));
// ---------^

Example:

function sum(arg1) {
    var sum = arg1;

    function f(arg2) {
        sum += arg2;
        return f;
    };

    f.valueOf = function () {
        return sum;
    };

    f.toString = function () {
        return sum;
    };

    return f;
}

console.log(sum(1)(2)(3)(4).valueOf());
// ------------------------^^^^^^^^^^

console.log(+sum(1)(2)(3)(4));
// ---------^
Look in the actual browser console; the Stack Snippets console doesn't quite do what the real browser console does.

Comments