How JavaScript Programs Work
- Combining Tasks with Functions
- Understanding Objects
- Handling Events
- Conditional Statements
- Loops
- Which Script Runs First?
- Workshop: Using Comments
- Summary
- Q&A
- Quiz
- Exercises
Welcome to the end of Part I of this book. In the first couple of hours, you've learned what JavaScript is, created a simple script, and learned the variety of things JavaScript can do.
In this, the final hour of Part I, you'll learn a few basic concepts and script components that you'll use in just about every script you write. This will prepare you for the remaining hours of the book, in which you'll explore specific JavaScript functions and features.
Hour 3 covers the following topics:
Organizing scripts using functions
What objects are and how JavaScript uses them
How JavaScript can respond to events
An introduction to conditional statements and loops
How browsers execute scripts in the proper order
Adding comments to document your JavaScript code
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.
NOTE
You will learn how to define, call, and return values from your own functions in Hour 4, "Using Functions and Variables."