Miroslav Trninic
Miroslav Trninic

Reputation: 3455

function.toString() in javascript

I don't understand how f.toString (without calling it) evaluate to returned result of that same function ?

function f(a){
    console.log(a + a);
    f.toString = function(){return a};// this part is       
//confusing.
    return f;
};

f(10) // 20
f(10)(20)// 20 40

Upvotes: 3

Views: 780

Answers (2)

SergeyS
SergeyS

Reputation: 3553

In fact f.toString is not even called in your scenario. If you will remove this line - result will be the same.

f.toString() will be called if you try to execute console.log(f);

Your results explained:

f(10) // 20

function f is called with argument 10, and it prints to console console.log(10 + 10);

f(10)(20) // 20 40

first part as above, but f function also returns itself return f; , it means that second part (20) will be treated as call to the same function one more time and it prints console.log(20 + 20);

Upvotes: 3

Quentin
Quentin

Reputation: 943214

If you try to use an object in a string context, then it will be converted to a string by calling it's toString() method.

See page 48 of the specification

Upvotes: 2

Related Questions