Chapter 3. Adding Logic and Control to Your Programs

So far you’ve learned about some of JavaScript’s basic building blocks. But simply creating a variable and storing a string or number in it doesn’t accomplish much. And building an array with a long list of items won’t be much help unless you have an easy way to work your way through the items in the array. In this chapter, you’ll learn how to make your programs react intelligently and work more efficiently by using conditional statements, loops, and functions.

Making Programs React Intelligently

Our lives are filled with choices: “What should I wear today?”, “What should I eat for lunch?”, “What should I do Friday night?”, and so on. Many choices you make depend on the situation. For example, say you decide you want to go to the movies on Friday night. You’ll probably ask yourself a bunch of questions like “Are there any good movies playing?”, “Is there a movie starting at the right time?”, “Do I have enough money to go to the movies (and buy a $17 bag of popcorn)?”

Suppose there is a movie that’s playing at just the time you want to go. You then ask yourself a simple question: “Do I have enough money?” If the answer is yes, you’ll head out to the movie. If the answer is no, you won’t go. But on another Friday, you do have enough money, so you go to the movies. This scenario is just a simple example of how the circumstances around us affect the decisions we make.

JavaScript has the ...

Get JavaScript & jQuery: The Missing Manual, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.