How to call a function in JavaScript?

JavaScript allows us to write our own functions as well. To invoke a function somewhere later in the script, you would simply need to write the name of that function.

Function Declaration

Before calling a function, you need to declare it. Here's the basic syntax:

function functionName() {
    // Code to execute
}

Calling a Function

Once declared, you can call a function by writing its name followed by parentheses:

<html>
<head>
    <script>
        function sayHello() {
            document.write("Hello there!");
        }
    </script>
</head>
<body>
    <p>Click the following button to call the function</p>
    <form>
        <input type="button" onclick="sayHello()" value="Say Hello">
    </form>
    <p>Use different text in write method and then try...</p>
</body>
</html>

Different Ways to Call Functions

Functions can be called in multiple ways depending on the context:

Direct Function Call

<script>
    function greetUser() {
        document.write("Welcome to our website!");
    }
    
    // Call the function directly
    greetUser();
</script>

Event-Driven Function Call

<button onclick="greetUser()">Click Me</button>

<script>
    function greetUser() {
        alert("Button clicked!");
    }
</script>

Functions with Parameters

Functions can also accept parameters when called:

<script>
    function greetWithName(name) {
        document.write("Hello, " + name + "!");
    }
    
    // Call function with argument
    greetWithName("John");
</script>

Common Methods

Method When to Use Example
Direct Call Execute immediately myFunction()
Event Handler User interaction onclick="myFunction()"
With Parameters Pass data to function myFunction(value)

Conclusion

Calling JavaScript functions is straightforward - just use the function name followed by parentheses. Functions can be called directly, through events, or with parameters to make them more flexible and reusable.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements