The toString() method returns a string representing the source code of the function.

Syntax

function.toString()

Return value

A string representing the source code of the function.

Description

The Function object overrides the toString method inherited from Object; it does not inherit Object.prototype.toString. For Function objects, the toString method returns a string representation of the object in the form of a function declaration. That is, toString decompiles the function, and the string returned includes the function keyword, the argument list, curly braces, and the source of the function body.

JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.

The toString() method will throw a TypeError exception ("Function.prototype.toString called on incompatible object"), if its this value object is not a Function object. It will also throw for Proxy objects, for example.

Function.prototype.toString.call('foo'); // TypeError

var proxy = new Proxy(function() {}, {});
Function.prototype.toString.call(proxy); // TypeError

If the toString() method is called on built-in function objects which aren't defined in ECMAScript code, toString returns a native function string which looks like this:

Math.abs.toString();

"function abs() {
    [native code]
}"

Specifications

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.1.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Function.prototype.toString' in that specification.
Standard Added more specific requirements for the string representation.
Function.prototype.toString revision Draft Standardizes native function string, line endings.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Function.prototype.toString' in that specification.
Living Standard  

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Revised support ? ? 54.0 (54.0) ? ? ?
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Revised support ? ? ? 54.0 (54.0) ? ? ?

Gecko-specific notes

  • Since Gecko 17.0 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14), Function.prototype.toString() has been implemented by saving the function's source. The decompiler was removed, so that the indentation parameter is not needed any more. See bug 761723 for more details.
  • Starting with Gecko 38 (Firefox 38 / Thunderbird 38 / SeaMonkey 2.35), Function.prototype.toString() throws for Proxy objects (bug 1100936).

See also

Document Tags and Contributors

 Last updated by: fscholz,