Chapter 4
Controlling the Flow of JavaScript
IN THIS CHAPTER
Setting up your code to make decisions
Understanding code looping
Setting up code loops
With the default script flow, the browser processes the code inside a script element or an external JavaScript file one statement at a time. The browser reads and then executes the first statement, reads and then executes the second statement, and so on until it has no more JavaScript left to read and execute.
That statement-by-statement flow seems reasonable, but it’s extremely limited. What if you want your code to test some condition and then branch to a specific chunk of code depending on the result of that test? What if you want your code to repeat some statements multiple times, with some change occurring in each repetition? Code that runs tests and code that repeats itself all fall under the rubric of controlling the flow of JavaScript. In this chapter, you explore this fascinating and powerful subject.
Decision-Making with if Statements
A smart script performs tests on its environment and then decides what to do next based on the results of each test. For example, suppose you’ve declared a variable that you later use as a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access