Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Combining Tasks with Functions

In the basic scripts you've examined so far, you've seen many JavaScript statements that have a section in parentheses, like this:

document.write("Testing.");

This is an example of a function. Functions provide a simple way to handle a task, such as adding output to a Web page. JavaScript includes a wide variety of built-in functions, which you will learn about throughout this book. A statement that uses a function, as in the example above, is referred to as a function call.

Functions take parameters (the expression inside the parentheses) to tell them what to do. Additionally, a function can return a value to a waiting variable. For example, the following function call prompts the user for a response and stores it in the text variable:

text = prompt("Enter some text.")

You can also create your own functions. This is useful for two main reasons: First, you can separate logical portions of your script to make it easier to understand. Second, and more importantly, you can use the function several times or with different data to avoid repeating script statements.

Share ThisShare This

Informit Network