Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Function

Function.prototype.toString()

Reference for JavaScript Function.prototype.toString(): get a function's source text, what native and bound functions return, and why you should not rely on it.

Function.prototype.toString() returns a string that represents the function. For functions written in JavaScript, that string is the exact source text of the definition, including comments, spacing and line breaks, exactly as it appears in the source file.

You rarely need it in application code. It is useful for debugging, for teaching tools that display a function next to its result, and for the occasional check whether a function is built in.

JavaScript
function add(a, b) {
  return a + b;
}
add.toString(); // "function add(a, b) {\n  return a + b;\n}"

Try it

JS Source text is kept exactly

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Native functions hide their code

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
func.toString()

Parameters: none.

Return value: a string. For a function defined in source code, it is the source text of the function (the function keyword or arrow parameters through the closing brace or expression, and for methods the method definition). For built-in and bound functions, it is a string of the form function name() { [native code] }, where the exact layout is implementation-defined.

Exceptions: a TypeError if toString is called on something that is not a function, for example Function.prototype.toString.call({}).

Usage notes

  • The text is not normalized. Comments, indentation and quotes come back as you wrote them, so the result depends on the file formatting.
  • Minifiers change it. After a build step the text is the minified code, not what you wrote. Do not parse it to find parameter names.
  • Classes return the whole class definition, including all methods.
  • Methods and getters return the method definition as written, such as greet(name) { ... }, not a standalone function.
  • Native and bound functions hide their code. Their result varies between engines, so a check for [native code] is a hint at best, not a security test.
  • Implicit conversion: string concatenation and template literals call it for you, as in "" + fn and `${fn}`.
  • Do not use it to serialize functions for later eval() or new Function(). Closures lose their captured variables, which breaks the function.

Browser support

Function.prototype.toString() is available everywhere. The exact text returned for native functions can differ slightly between engines.