We can use the toString()
method on a function object to get the source code of a function.
function test(a, b){console.log("hi");}console.log(test.toString());
If we concatenate a string with a function, JavaScript will call the toString()
method on the function internally and convert the function to a string.
function test(a, b){console.log("hi");}console.log(test + "hello");
When calling the toString()
method with this
as a non-function object, we will get a TypeError. This is because the function was called on an incompatible object type.
function test(a, b){console.log("hi");}console.log("Calling Function.prototype.toString with function value \n" + Function.prototype.toString.call(test));console.log("\n--------\n")try{console.log("Calling Function.prototype.toString with non-function value")console.log(Function.prototype.toString.call(1));} catch(e){console.log(e.message);}
If the toString()
method is called on built-in function objects, a “native code” string is returned.
console.log("Calling toString on in-built function ");console.log(parseInt.toString());
If the toString()
method is called on functions created by the bind method, it will also return a “native code” string.
function test(a, b){console.log(this.a);}var a = test.bind({a: 20}, 1, 2);console.log("Calling to string on function created from bind")console.log(a.toString());
toString()
can also be called on arrow functions and generator functions.
var arrow = (a, b)=>{console.log("hi");}console.log("Arrow function ");console.log(arrow.toString());function* generator(i) {yield i;yield i + 10;}console.log("\n----------\nGenerator function");console.log(generator.toString());// please try this in console