Develop JavaScript to implement functions

Laboratory Objective:

  1. To be able to understand the concept of functions.
  2. To develop JavaScript to implement the given function.
  3. To develop JavaScript to calling function from HTML.
  4. To be develop JavaScript to returning a value from a function.

JavaScript Functions

  • A function is block of code designed to perform a particular task.
  • It is reusable code which can be called anywhere in program.
  • There are two types of functions:
    1) Built-in functions
    2) User-defined functions

Defining a function

  • A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
  • Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
  • The parentheses may include parameter names separated by commas: (parameter1, parameter2, …)
  • It is recommended that the function should define in <head> tag.
  • A function definition consists of four parts:
    1) Function name
    2) Parenthesis
    3) Code block
    4) Return statement (Optional)
  • Syntax:

function  functionName([arg1, arg2, ...argN])

{

 // code to be executed

 return val;

}

  • Example:

function cube(a)

{

   document.write(a*a*a);

}

Function without arguments

<html>

<head>

  <script>

     function msg()

     {

        alert("Hi, Welcome to JavaScript");

     }

  </script>

</head>

<body>

<input type="button" onclick="msg()" value="Call Function"/>

</body>

</html>

Function with arguments

<html>

<head>

  <script>

     function cube(num)

     {

         alert(num*num*num);

     }

  </script>

</head>

<body>

<input type="button" onclick="cube(4)" value="Find Square"/>

</body>

</html>

Function with a return value

<html>

<head>

  <script>

     function getSquare(s)

     {

        return s * s;

     }

     document.write(getSquare(9));

     </script>

</head>

<body>

</body>

</html>

Sample Programs

1) Develop a program to create a function sum which takes two parameters as number and display the addition numbers provided

<html>

<head>

   <script>

       function sum(val1, val2) {

           var result = val1 + val2;

           document.write(result + "<br/>");

       }

   </script>

</head>

<body>

   <script>

       sum(23, 19);

       sum(32, 56);

       sum(12, 52);

   </script>

</body>

</html>

2) Develop a program to convert temperature from Celsius to Fahrenheit by returning value from function.

<html>

<head>

   <script>

       function toFahrenheit(celsius) {

          return (celsius * 9/5 + 32);

       }

       document.write("Temperature in Fahrenheit is " +

                                       toFahrenheit(45));

   </script>

</head>

<body>

</body>

</html>