About FunctionsBefore you get into the next example, you need to learn a bit about functions, which you'll use often when writing JavaScript. A function is a set of JavaScript statements that performs a task. Every function must be given a name (with one very rare exception, which we'll discuss much later in this book) and can be invoked, or called, by other parts of the script. Functions can be called as many times as needed during the running of the script. For example, let's say that you've gotten some information that a user typed into a form, and you've saved it using JavaScript (there's more about this sort of thing in Chapter 7, "Form Handling"). If you need to use that information again and again, you could repeat the same code over and over in your script. But it's better to write that code once as a function and then call the function whenever you need it. A function consists of the word function followed by the function name. There are always parentheses after the function name, followed by an opening brace. The statements that make up the function go on the following lines, and then the function is closed by another brace. Here's what a function looks like: function saySomething() { alert("Four score and seven years ago"); } Notice that the line with alert is indented? That makes it easier to read your code. All of the statements between the first brace and the last one (and you probably noticed that those two lines are not indented) are part of the function. That's all you need to know for now about functions. You'll learn more about them in the next and subsequent chapters. |