Functions in JavaScript

What are functions?

In our previous topics we have learnt about loops and some control statements like break and continue. Now, JavaScript provides another most important facility which are known as functions.

Functions are groups of codes which can be written separately from main program and can be called anywhere in the program. When someone is called by his senior in any office to perform some work, in the same way a function is also called in the main program to perform a particular task. Functions eliminate the need of writing same code again and again in the main program and whenever required can be called from outside of main program.

Functions allow programmers to write a large program in small parts which are called as modules. Like other programming languages, JavaScript also supports to write functions in the code. Functions provide a better way to write a reusable code which are portable and easier to debug as it is easy to find out error in small code instead of big code.

Let us write some advantages of writing a function.

  1. Functions reduce the repetition of same code in main part of program and therefore reduces duplicity of code.
  2. Functions make the code much easier to maintain.
  3. Functions makes it easy to find an error in code and to correct it within minimum time span.
  4. Helps in developing code in a short period of time as many number of programmers can work separately on different functions used in the code.

Defining and calling a function

Defining a function

The function must be defined before using it in the program. It can be defined by using a keyword function followed by the name of the function which you want to give followed by parameters within () and block of statements within {} brackets. The syntax for declaring a function is given as below:

function functionname()

{

block of statemetns

}

<script type = "text/javascript">
      function Hello() {
         alert("Hello there");
      }
</script>

Calling a function

Once the function is defined, you need to call it in the main program by its name followed by () like hello(). Let us understand to call a function by using a small code which is greeting your friend after clicking the button.

<html>
   <head>   
      <script type = "text/javascript">
         function greet() 
         {
            document.write ("Happy new year");
         }
      </script>  
   </head> 
   <body>
      <p>Click the following button to call the function</p>      
      <form>
         <input type = "button" onclick = "greet()" value = "Greet your friend">
      </form>      
   </body>
</html>

It will say Happy new year when you click the button after running above code. In this code the function greet() is called with a value “Greet your fried”. When the button is clicked the function greet() invoked and it produces output as “Happy new year”.

Function parameters

Function parameters are nothing but the values which we are passing to the defined function. In above code, we have not passed any parameters to the function greet() but if it is required you can pass parameters also. These parameters are to pass while calling a function and any manipulation can be done over these parameters. Multiple parameters can pass by separating the parameters by comma. Let us now write a simple code which shows passing parameters in function.

The syntax is given below

function functionName(parameter1, parameter2, parameter3)

{
    // Code to be executed
}

<html>
   <head>   
      <script type = "text/javascript">
         function employee(name, age) {
            document.write (name + " is " + age + " years old.");
         }
      </script>      
   </head> 
   <body>
      <p>Click the following button to call the function</p>      
      <form>
         <input type = "button" onclick = "employee('Ayush', 25)" value = "Get employee">
      </form>      
   </body>
</html>

In this code, a function employee() is called with parameters (‘Ayush’, 25). These parameters have been passed to the function employee(name, age). As the function is called, Ayush will be passed to the variable ‘name’ and 25 will be passed to the variable ‘age’ and finally prints a statement “Ayush is 25 years old” when clicked on button showing “Get employee”.

You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called, otherwise its value becomes undefined.

// Defining function function 
Fullname(firstName, lastName) 
{ 
alert(firstName + " " + lastName); 
} 
// Calling function 
Fullname("Vijay", "Kumar"); // 0utputs: Vijay Kumar
Fullname("Vijay"); // 0utputs: Vijay undefined

Setting default value of function

A default value can be given to the function when no parameters have been passed to the defined function. If some new value is passed to the function, the default value will get replaced by passed value.

function Hello(name = 'Guest') 
{ 
alert('Hello, ' + name); 
} 
Hello(); // 0utputs: Hello, Guest 
Hello('Vijay'); // 0utputs: Hello, Vijay

return statement in JavaScript

The return keyword is used in function if you want to return a value from a function. This is an optional statement and it should be the last statement in the function. The value may be of any type including arrays and objects. A small program to add numbers is written below:

<html>
<head>
    <script type="text/javascript">
        function calculate(num1, num2) {
            var total = num1 + num2;
            return total;
        }
    </script>
</head>
<body>
    <script>
        var x = calculate(7, 15);
        document.write("The value of first function is ", x, "</br>");
        var y=calculate(-7, -10);
        document.write("The value of second function is ", y);
    </script>
</body>
</html>

Output:

The value of first function is 22
The value of second function is -17

It should be noted that a function cannot return multiple values but you can obtain similar results by returning array of values which is shown below in code.

<html>
<head>
    <script type="text/javascript">
        function calculate(num1, num2) {
            var total = num1 + num2;
            var arr=[num1, num2, total];
            return arr;
        }
    </script>
</head>
<body>
    <script>
        var x = calculate(7, 15);
        for(i=0;i<=2;i++)
        {
            document.write("The value at position ",i+1, " is ", x[i], "</br>");
        }
    </script>
</body>
</html>

Output:

The value at position 1 is 7
The value at position 2 is 15
The value at position 3 is 22

Scope of variable in function

You can declare variable anywhere in your code depending upon the extent of using the variable in the code. If you want to use the variable locally in the function, you can declare it within the function area but that variable can be used within that function area only. If you want to use variable anywhere in the code then you have to declare it as globally. Let us understand by taking example of both locally and globally declared variables.

<html>
<head>
    <script type="text/javascript">
        function calculate(num1, num2) {
            var total = num1 + num2;
        }
    </script>
</head>
<body>
    <script>
        var x = calculate(7, 15);
        document.write("The sum of two numbers is ", total);      
    </script>
</body>
</html>

In above code, the variable is declared within the defined function area and we are printing it where the function is called. In such case, you won’t get your result. In next code, we are declaring the variable globally to get our result.

<html>
<head>
    <script type="text/javascript">
    var total;
        function calculate(num1, num2) {
            total = num1 + num2;
        }
    </script>
</head>
<body>
    <script>
        var x = calculate(7, 15);
        document.write("The sum of two numbers is ", total);      
    </script>
</body>
</html>

Output:

The sum of two numbers is 22