User defined simple functions In Java Script

Function is a set of statements recognized by a name and can be used as and when required (it is reusable). In JavaScript functions can be created inside the JavaScript tag only. “function” is a reserve word after which we type the name of the function to be created and then brackets. The code from where the function starts and where ends is kept in side curly braces.
 
Syntax:
 
function functionname()

{

lines to be kept under this name

}

 
Example:
 
<html>

<head>

</head>

<body>

<script type=”text/javascript”>

function ff()

{

document.write(“Have a nice day”);

}

  function pp()

{

document.write(“Try again”);

}

var a

a=parseInt(prompt(“Enter value”,””));

if(a>10)

{

ff()

}

else

{

pp()

}

</script>

</body>

</html>

 
Understanding program:
In the above program ff function is being called if the value entered is more than 10 else pp function is called. Function ff contains a line showing a message “have a nice day” and function pp contains a line showing messages “Try again “ , so which function will be called depends on the value entered.
 
Output is:
If value entered is more than 10 then
Have a nice day
Else
Try again
Click here to view result of this program on browser
 
Example
 
<html>

<head>

</head>

<body>

<script type=”text/JavaScript”>

function ff()

{

document.bgColor=”red”;

}

</script >

<input type=”Button” value=” Hit me” name=”b1″ onClick=”ff()”>

</body>

</html>

 
 
Understanding program:
We created a button and onclick event of that button we called the function ff() , in which we have typed that the background color of the document should be turned to red.
Scroll to Top