Functions in Javascript
Functions in Javascript
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.
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.
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>