Page 207 - Web Applications (803) Class 12
P. 207
3.12 FUNCTIONS IN JAVASCRIPT
A block of code created specifically to carry out a specific task is referred to as a JavaScript function. If
“something” calls a JavaScript function, it will be executed (function call).
The function keyword, a name, and then parentheses define a JavaScript function().
Syntax:
function name(parameter1, parameter2, …………) {
// code to be executed
}
Numerals, underscores, dollar signs, and letters are all permitted in function names (same rules as variables).
Parameter names can be included in parenthesis, with commas separating them as shown above.
Curly brackets, {}, surround the code that will be executed by the function.
The values that the function receives when it is called are known as parameters/arguments for the function.
Invoking a function
When “something” invokes (calls) the function, the code inside it will run. This happens in the following scenarios:
When an event happens (a user clicks a button)
When JavaScript code calls (invokes) it
Automatically (self-invoked)
Example:
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This code calls a function which multiplies two numbers</p>
<script>
function myFunction(p1, p2) //Function definition
{
document.write("The product is "+(p1*p2)); //Function body
}
myFunction(4, 3); //Function call
</script></body>
</html>
Output of the preceding program is as follows:
Web Scripting—JavaScript 205

