JavaScript Function toString()

The JavaScript Function toString() method returns the source code of the function as a string.

The syntax of the toString() method is:

func.toString()

Here, func is a function.


toString() Parameters

The toString() method does not take any parameters.


Return value from toString()

  • Returns a string representing the source code of the function.

Example: Using toString()

function f() {}
console.log(f.toString()); // function f() {}

function sum(a, b) {
  return a + b;
}
console.log(sum.toString());
// function sum(a, b) {
//  return a + b;
// }

// built-in functions
console.log(console.log); // log() { [native code] }

console.log(Function.prototype.toString); // toString() { [native code] }

console.log((() => "Hello World!").toString()); // () => "Hello World!"

Output

function f() {}
function sum(a, b) {
  return a + b;
}
log() { [native code] }
toString() { [native code] }
() => "Hello World!"

Recommended Reading: JavaScript Object toString()

Did you find this article helpful?