toString() on a function
What Function.prototype.toString() does
The toString() method returns a string representation of the function's source code.
In other words, it converts the function into a string.
Example 1 - a simple function
function sum(a, b) {
return a + b;
}
console.log(sum.toString());Output:
"function sum(a, b) {
return a + b;
}"Example 2 - an arrow function
const multiply = (a, b) => a * b;
console.log(multiply.toString());Output:
"(a, b) => a * b"Example 3 - an anonymous function
console.log(function(x) { return x ** 2; }.toString());Output:
"function (x) { return x ** 2; }"Example 4 - built-in (native) functions
If you call toString() on a built-in JavaScript function (for example, Math.max),
you will not see the source code, but you will get a special string:
console.log(Math.max.toString());Output:
"function max() { [native code] }"This means the function is implemented at the engine level (C++), not in JS.
Example 5 - on classes and methods
class User {
sayHi() {
console.log('Hello!');
}
}
console.log(User.toString());Output:
"class User {
sayHi() {
console.log('Hello!');
}
}"Behavior per the standard (ECMAScript 2019+)
Previously, browsers returned different formats (they could strip whitespace, line breaks, and so on), but starting with ES2019 (ES10):
Function.prototype.toString()returns an exact textual copy of the source code, including whitespace, comments, and formatting.
Why this is needed
| Use | Example |
|---|---|
| Debugging | You can print a function's source code to the console |
| Inspecting content | For example, for analysis or serialization |
| Metaprogramming | Generating new functions "based on" others |
| Built-in tools | Some frameworks use toString() to extract arguments or a function's body (for example, Angular before ES6) |
Example 6 - use in metaprogramming
function greet(name) {
return `Hello, ${name}`;
}
const src = greet.toString();
console.log(src); // source code
const copy = new Function('return ' + src)();
console.log(copy('Tim')); // Hello, TimHere we serialized the function into a string, then created a new one from it via new Function.
Important to remember
toString()returns the source code, not a "compiled" variant.- For built-in functions,
"[native code]"is returned. - For class methods and generators, the format matches the declaration.
- Arrow functions and methods with
=>are returned as is, withoutfunction.
Summary
| What it does | Returns the function's source code as a string |
|---|---|
| Return type | string |
| Works with | Regular functions, arrow functions, methods, classes |
| For built-in functions | function ... { [native code] } |
| Standard | Since ES2019 returns the exact source text |
| Common uses | Debugging, code analysis, metaprogramming |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.