Chapter 4. Controlling Flow

Running a forest trail in May, I startled a doe and her newborn fawn. The doe made a raspy snort to warn the fawn of danger. Not knowing what to do, the fawn wobbled over to me and plopped down between my legs. Trembling with fear, it looked up at me and bleated faintly, imploring me to keep it safe. The doe stood 20 yards off, quivering with agitation. Obviously, it had wanted the fawn to run away from the predator, not to it.

JavaScript is like the newborn fawn in that it does not know which way you want it to run. So by default, it will simply run forward—that is to say, from the first line in your script to the last. However, there are four ways to manipulate this mindless, sequential flow.

First, you can send JavaScript ...

Get JavaScript for Absolute Beginners 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.