The toString()
method returns the source code of the function as a string.
Example
function sum(a,b){
return a + b;
}
// returns the source code of sum() function
console.log(sum.toString());
// Output:
// function sum(a,b){
// return a + b;
// }
toString Syntax
The syntax of the toString()
method is:
func.toString()
Here, func
is a function.
toString() Parameters
The toString()
method does not take any parameters.
toString() Return Value
- Returns a string representing the source code of the function.
Example 1: Using toString() Method
// function definition
function hello() {
console("Good morning.");
}
// prints the source code of the hello() function
console.log(hello.toString());
Output
function hello() { console("Good morning."); }
In the above program, we have defined the function hello()
and then called the toString()
method as hello.toString()
.
The toString()
method returns the whole source code of hello()
.
Example 2: toString() with Arrow Functions
// toString with arrow function
console.log((() => "Hello World!").toString());
Output
() => "Hello World!"
In the above example, we have used the toString()
method with the arrow functions.
Here, the method returns the whole source code of the given arrow function.
Recommended Reading: JavaScript Object toString()