How to call functions in JavaScript?

A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code repeatedly. It helps programmers in writing modular codes.

The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Here’s an example −

      function sayHello() {
         alert("Hello there");

To call a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code.


Here’s an example showing how to call a function in JavaScript

Live Demo

         function sayHello() {
         d ocument.write ("Hello there!");

      <p>Click the following button to call the function</p>
         <input type = "button" onclick = "sayHello()" value = "Say Hello">
      <p>Use different text in write method and then try...</p>