JavaScript Function toString() Method

The `toString()` method in JavaScript is used to return a string representing the source code of the function. It provides a way to convert a function to its string representation, which can be useful for debugging or inspecting the function's code.

Syntax


function.toString()  

                  

Key Features of toString():

Example of toString() Method:

This example demonstrates how to use the `toString()` method to get the source code of a function:

Example


function add(a, b) {
    return a + b;
                }

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

Output

function add(a, b) {
    return a + b;<br> }

When to Use toString():

The `toString()` method is useful when you need to inspect or log the function code. It’s particularly helpful for debugging, as it allows you to see what’s inside a function without executing it. You can also use it in development tools that display or analyze code.