Functions in JavaScript

In this tutorial, we will learn the Functions in JavaScript. Main purpose to use function is to reuse the code. For example, you have a large program where you want to perform the sum of two number multiple times. You can do this with the help of function without writing the same piece of code multiple times.

Functions help us to divide the big program into pieces. It is easy to manage a small piece of code instead of a big program. There are also a lot of inbuilt functions like alert() or write(). As we know we use these function several times but they are defined only once in core JavaScript. We will learn four things in these tutorials.

  • Function Destination
  • Calling a function
  • Functions with parameters
  • Return Statement of Functions

Function Destination:

It is obvious if we want to use a function then we first have to define those functions. It is so easy to define a function in JavaScript. You just need to function keyword then write function name. You can also write parameters if that is the requirement of your function. Now we will check a simple example if JavaScript function

<script>
      function show() {
         alert("Hello This show Method");
      }
</script>

Calling a function:

In the last example, we saw how we can define a function in our code. Now the second step after creating a function is how to call these functions. Calling a function is so easy you just need to write the function name followed by parentheses where you want to call that function.

<script>
   function show() {
      document.write ("Hello This show Method");
   }
</script> 
   
<form>
     <input type="button" onclick="show()" value="Call show Method">
</form>  

Functions with parameters: 

Till now we learnt how we can create a function and how we can call that function. But showtimes we also want to send data to function when we call that function and we want the function to process that data which we sent while the call to that function. So to do this we define parameter functions is our code. Check this Example of Parameter functions.

<script>
   function add(num1, num2) {
      document.write ("Sum ="+ (num1+num2) );
   }
</script>      
    
<form>
   <input type="button" onclick="add(10, 15)" value="Show Sum">
</form>      

Return Statement of Functions:

In many situations, we need our functions should return some value after completing the whole process in function in that kind of situations we use the return statement.

<script>
   function add(num1, num2) {
     var sum;
     sum = num1 + num2;
     return sum;
   }
   function show() {
      var result;
      result = add(15,20);
      document.write (result );
    }
</script>      
   
<form>
   <input type="button" onclick="show()" value="Show Sum">
</form>    
Spread the love