javascript toString method in ES10
Each object extends the Object.prototype using object inheritance.Object.prototype has toString method. Each object inherits the toString() method in javascript. A function is also an object in javascript, Function toString() returns source code without comments, spaces, commas, and new lines before the ES10 version.
ES10 enhanced the 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 the string representation of a given function name
function getMessage(msg) {
var name = msg;
// display name to console
console.log(`Hello ${name}`);
}
toString method returns the string version of an object.
It is used to convert a number to a String.
Printing function definition on inbuilt native calls
toString() method is called for the below use cases
- using an inbuilt function name
- bind context
- Inbuilt objects
if toString() is called on inbuilt function names instead of function calls, It prints the 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 of displaying an 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(
) {
}