JavaScript: Functions, Status |
S F S |
Functions |
Functions play a key role in most programming languages, and JavaScript is no different. A function can be thought of as a chunk of code that performs a specific task. Whenever you need the task to be done, you summon the function to do the task. For example, you could write a function that figures out today's date in mm/dd/yyyy format. You could write a function that combines a first name and a last name and prints the result to the screen using "alert()." It makes sense to write a function to do something that you may want to use more than once.
Let's get introduced to the syntax of a function. Here is a script that uses a function that multiplies 2 numbers together and displays the result using "alert()":
<head>
<script language=JavaScript>
function mult(x, y)
{
var z;
z = x * y;
alert('The product of ' + x + ' and ' + y + ' is ' + z);
}
</script>
</HEAD>
<BODY>
<script language=JavaScript>
<!--
x = prompt("Please give me a number", " ");
y = prompt("Please give me a second number"," ");
mult(x, y);
//-->
</script>
</body>