A function is a
group of reusable code which can be called anywhere in our program. This eliminates the need of writing the same
code again and again. It helps programmers in writing modular codes.
Functions allow a programmer to divide a big program
into a number of small
and manageable functions.
Syntax
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
Example
It defines a function called
sayHello that takes no parameters---
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>
Calling a function
<html>
<head>
<script type="text/javascript">
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>
Output
A function can take multiple parameters separated by comma.
Example
<html>
<head>
<script type="text/javascript"> 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('Avishek', 7)" value="Say Hello">
</form>
</body>
</html>
Output
Take user input from Prompt window
<!DOCTYPE html>
<html>
<head>
<script>
function fun() {
var facultyName = prompt("Please enter your name", "");
if (facultyName!= null) {
document.getElementById("welcome").innerHTML =
"Hello " + facultyName + "! How are you today?";
}
}
</script>
</head>
<body>
<div id="welcome"></div>
<button onclick = "fun()">
Click me
</body>
</html>
Output
No comments:
Post a Comment