How to call a JavaScript Function from Chrome Console?

You can call JavaScript functions directly from the Chrome Developer Console. This is useful for testing, debugging, and interacting with functions defined in your web page or application.

Opening Chrome Developer Console

To access the console, press F12 or Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac), then click the Console tab.

Calling Functions from Console

Once a function is defined in your page's JavaScript, you can call it directly from the console by typing the function name followed by parentheses.

<!DOCTYPE html>
<html>
   <body>
      <script>
         // Define a simple function
         function greetUser(name) {
            return "Hello, " + name + "!";
         }
         
         // Define an object with methods
         var calculator = {
            add: function(a, b) {
               return a + b;
            },
            multiply: function(a, b) {
               return a * b;
            }
         };
         
         console.log("Functions are now available in the console");
      </script>
   </body>
</html>
Functions are now available in the console

Example Console Commands

After loading the above HTML page, you can type these commands directly in the Chrome console:

// Call the greetUser function
greetUser("Alice");
// Returns: "Hello, Alice!"

// Call object methods
calculator.add(5, 3);
// Returns: 8

calculator.multiply(4, 7);
// Returns: 28

// Call functions without parameters
calculator.add(10, 20);
// Returns: 30

Working with Global Functions

Functions declared in the global scope (not inside other functions) are accessible from the console:

<!DOCTYPE html>
<html>
   <body>
      <script>
         // Global function
         function showAlert(message) {
            alert("Message: " + message);
            return "Alert shown";
         }
         
         // Function that modifies DOM
         function changeBackgroundColor(color) {
            document.body.style.backgroundColor = color;
            return "Background changed to " + color;
         }
      </script>
   </body>
</html>

Key Points

  • Functions must be defined before you can call them from the console
  • Both regular functions and object methods are accessible
  • You can pass parameters to functions just like in regular JavaScript
  • The console will display the return value of the function
  • Use the console for quick testing and debugging of your functions

Conclusion

The Chrome console provides direct access to call any JavaScript function defined in your page. This makes it an invaluable tool for testing and debugging your code interactively.

Updated on: 2026-03-15T22:13:06+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements