ES10 - Function.toString

This tutorial covers Function toString introduced ES2019 with examples..

Function.toString() method in javascript

Each object extends Object.prototype using object inheritence.Object.prototype has toString method. Each object inherits toString() method in javascript.Function is also an object in javascript, Function toString() returns source code without comments, spaces, commas and new lines before ES10 version.

ES10 enhanced toString() method which returns the source of the function with preserving comments and blank/new lines example

function getMessage(msg) {
    var name = msg;
    // display name to console
    
    console.log(`Hello ${name}`);
}
console.log(getMessage.toString());

Output is string representation of given function name

function getMessage(msg) {
    var name = msg;
    // display name to console
    
    console.log(`Hello ${name}`);
}

Printing function definition on inbuilt native calls

toString() is called for below use cases

  • using inbuilt function name
  • bind context
  • Inbuilt objects

if toString() is called on inbuilt function names instead of function calls, It prints function header with includes native code as follows

// functions name to string example
console.log(" test".padStart.toString()); 
//outputs function padStart() { [native code] }

// bind context toString example
console.log(function () { }.bind(1).toString()); 
//Outputs function () { [native code] }

// Object toString example
console.log(Function.toString()); 
//Outputs function () { [native code] }

Anonymous functions toString

The following is an example for displaying anonymous function definition Function constructor is created and called toString() method Outputs function definition with anonymous keyword init

console.log(Function().toString()); 
**Outputs**
function anonymous(
) {

}