Nimisha Manan
Asst. Professor
Deptt. Of Computer Science
A JavaScript function is a block of code designed to
perform a particular task.
One of the fundamental building blocks in JavaScript.
A JavaScript function is executed when "something"
invokes it (calls it).
Functions allow a programmer to divide a big
program into a number of small and manageable
modules.
To use a function, it must be defined somewhere in
the scope from which it has to be called.
Syntax :-
function functionname(parameter-list)
{ statements }
Example :-
<script type = "text/javascript">
function sayHello()
{ alert("Hello there"); }
</script>
The code inside the function will execute when
"something" invokes (calls) the function:
◦ When an event occurs (when a user clicks a
button)
◦ When it is invoked (called) from JavaScript
code
<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>
When JavaScript reaches a return statement,
the function will stop executing.
If the function was invoked from a statement,
JavaScript will "return" to execute the code
after the invoking statement.
Functions often compute a return value. The
return value is "returned" back to the "caller":
Calculate the product of two numbers, and return
the result:
var x = myFunction(4, 3);
// Function is called, return value will be assigned to x
function myFunction(a, b)
{
return a * b;
// Function returns the product of a and b
}
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last)
{ var full;
full = first + last;
return full;
}
function secondFunction()
{ var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form> <input type = "button" onclick = "secondFunction()"
value = "Call Function">
</form>
</body>
</html>