How to call functions in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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 −

<script>
   <!--
      function sayHello() {
         alert("Hello there");
      }
   //-->
</script>

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.

Example

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

Live Demo

<html>
   <head>
      <script>
         function sayHello() {
         d ocument.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>
raja
Published on 24-Jan-2018 06:42:23
Advertisements