What is Control Flow?
A fundamental skill in programming is controlling how a program executes. The control of program execution is categorized using three control structures. They are "sequential", "selection", and "repetition". So far, you've written straightforward code that uses sequential JavaScript statements that execute one after another. More complex decision-making programs use selection and repetition. Programs also implement different types of looping structures, such as looping until some condition is met (sentinel) or looping a specific number of times (counter control). As you read through this section, you should notice that control structures in JavaScript use "reserved keywords" (if, else, switch).
Updating bindings succinctly
Especially when looping, a program often needs to "update" a binding to hold a value based on that binding's previous value.
counter = counter + 1;
JavaScript provides a shortcut for this.
counter += 1;
Similar shortcuts work for many other operators, such as result *= 2
to double result
or
counter -= 1
to count downward.
This allows us to shorten our counting example a little more.
for (let number = 0; number <= 12; number += 2) { console.log(number); }
For counter += 1
and counter -= 1
, there are even shorter equivalents: counter++
and counter--
.