USE FUNCTIONS
All Web programming languages, including, JavaScript, use functions.
Functions are an efficient way to use and store blocks of code statements.
JavaScript includes many built-in functions, such as prompt, and
you can also create your own functions for code blocks that you want to
reuse.
Function definitions are usually included in script blocks in the head section of a page -- other than JavaScript's built-in functions, a function must be defined before it can be used. Because the code in the head section is executed before the code in the body section, functions are usually defined in the head section and called (invoked) from the body section.
To create a function, you must define it and give it a name, such as the following
function myCat (catname) {
alert
(catname + " is a great name for a cat!");
}
A function includes the following:
- A name: myCat
- Parameters: the variable(s) inside the parentheses that follow the function's name: catname
- A code block between curly braces: { alert (catname + " is a great name for a cat!");}
The function definition is everything in between the opening and closing
curly braces { }.Even if there are no parameters for a
particular function, you must use the parentheses after the function name.
To invoke a function, use the function's name in a script statement, such as:
myCat("Fluffy");
In this case, you give the catname variable the value of
"Fluffy" when you call the myCat function.
You can return a value from a function by using a return
statement, such as:
function quatro (item) {
var IV;
IV = item * 4;
return IV;
}
Obviously, a function to multiply by 4 is not particularly useful, but this should illustrate the basic idea.
A function should always include a return statement, even if no
value is being returned, such as:
function myCat (catname) {
alert (catname + " is a great name for a cat!");
return;
}
Moving On
In this lesson, you learned how to use a prompt to get input from users as
well as how to display this information by using an alert box or writing the
information directly to the Web page with a document.write
statement. You also learned the basics of functions.
In the Lesson 4, you'll learn how to create conditions to respond in different ways to different input, and make loops to automate activities.
Before you move on, don't forget to do the assignment and take the quiz. In addition, visit the Message Board to check in with your fellow students.
