Tuesday, December 12, 2017

JavaScript Functions - Day 18

Function is a line of code which is write for one time & can be reused again & again. So, these functions eliminates writing a specific code again & again in a program.
How to Write a Function...??/
We have to start with "function" keyword and then we have to name the function. Then a parameter which contain parameters or null should be written.. after that curly braces should be wriiten..

<script>
      function functionname  parameter-list  )
      {
         statements
      }
</script>

Calling Function
So, now you have write the Function and then you have to call the function anywhere in the program to run.
Simply, you have to type the name of the function with parenthesis ()

<html>
   <head>
      <script>
         function sayHello()
         {
            document.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>
   </body>
</html>

Function With Parameters

Still we haven't put any parameters inside the function.So, now we have to practice with parameters
There is a way to insert parameters; when calling function inside parenthesis you can put the argument.

<html>
   <head>
      <script>
         function sayHello(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="sayHello('Parathan', 19)" value="Say Hello">
      </form>
   </body>
</html>
Click the following button to call the function


Return Statement inside a Function

If you want to get a statement from function you have to code this at the bottom of the function where it ends.
For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program.

<html> 
<head> 
<script>
 function firstFunction(first, last) {
 var full; full = first + last; 
return full; 
function lastFunction() { 
var result; 
result = firstFunction('Parathan', 'Thiyagalingam'); 
document.write (result ); 
}
 </script> 
</head> 
<body> 
<p>Click the following button to call the function</p> <form> 
<input type="button" onclick="lastFunction()" value="Call Function"> </form>
</body> 
</html>

Click the following button to call the function

No comments:

Post a Comment