Branching and iteration
Overview
In this module we will consider more complex flow of controlThe order in which instructions are executed., namely branching and iteration. Since JavaScript does not differ from other languages in these aspects, we'll cover the syntax and then use the features to create more interesting examples.
If you are already comfortable with the programming concepts of branching and iteration, please proceed to the next step.
In-depth background from our introductory programming course
Brief review of programming concepts: branching
A program contains branching when there are multiple possible courses of action.
BooleanA type of data with two possible values. conditionsA Boolean expression used to make a choice. are used to determine which course of action should be taken. Sometimes multiple conditions are used to divide action into multiple branches.
When the branching ends, the courses of action rejoin.
Brief review of programming concepts: iteration
When a program repeats a sequence of steps, perhaps on different data, the program is said to use iteration.
Programming languages tend to use two main kinds of iteration:
- while loops continue iterating while a Boolean condition is true
- for loops continue iterating for a fixed number of iterations
Each loop consists of a loop header, which specifies how the loop operates, and a loop body, which is the sequence of steps to be executed. Each time the steps in the loop body are executed is considered one iteration of the loop.
Depending on the programming language, there may be different kinds of while loops, varying by when the condition is checked. There may also be ways to exit early from a particular iteration of a loop or from the entire loop.