Please support this book: buy it or donate

21. Control flow statements



This chapter covers the following control flow statements:

  • if statements (ES1)
  • switch statements (ES3)
  • while loops (ES1)
  • do-while loops (ES3)
  • for loops (ES1)
  • for-of loops (ES6)
  • for-await-of loops (ES2018)
  • for-in loops (ES1)
    Before we get to the actual control flow statements, let’s take a look at two operators for controlling loops.

21.1. Controlling loops: break and continue

The two operators break and continue can be used to control loops and other statements while you are inside them.

21.1.1. break

There are two versions of break: one with an operand and one without an operand. The latter version works inside the following statements: while, do-while, for, for-of, for-await-of, for-in and switch. It immediately leaves the current statement:

  1. for (const x of ['a', 'b', 'c']) {
  2. console.log(x);
  3. if (x === 'b') break;
  4. console.log('---')
  5. }
  6. // Output:
  7. // 'a'
  8. // '---'
  9. // 'b'

21.1.2. Additional use case for break: leaving blocks

break with an operand works everywhere. Its operand is a label. Labels can be put in front of any statement, including blocks. break foo leaves the statement whose label is foo:

  1. foo: { // label
  2. if (condition) break foo; // labeled break
  3. // ···
  4. }

Breaking from blocks is occasionally handy if you are using a loop and want to distinguish between finding what you were looking for and finishing the loop without success:

  1. function search(stringArray, suffix) {
  2. let result;
  3. search_block: {
  4. for (const str of stringArray) {
  5. if (str.endsWith(suffix)) {
  6. // Success
  7. result = str;
  8. break search_block;
  9. }
  10. } // for
  11. // Failure
  12. result = '(Untitled)';
  13. } // search_block
  14. return { suffix, result };
  15. // same as: {suffix: suffix, result: result}
  16. }
  17. assert.deepEqual(
  18. search(['foo.txt', 'bar.html'], '.html'),
  19. { suffix: '.html', result: 'bar.html' }
  20. );
  21. assert.deepEqual(
  22. search(['foo.txt', 'bar.html'], '.js'),
  23. { suffix: '.js', result: '(Untitled)' }
  24. );

21.1.3. continue

continue only works inside while, do-while, for, for-of, for-await-of and for-in. It immediately leaves the current loop iteration and continues with the next one. For example:

  1. const lines = [
  2. 'Normal line',
  3. '# Comment',
  4. 'Another normal line',
  5. ];
  6. for (const line of lines) {
  7. if (line.startsWith('#')) continue;
  8. console.log(line);
  9. }
  10. // Output:
  11. // 'Normal line'
  12. // 'Another normal line'

21.2. if statements

These are two simple if statements: One with just a “then” branch and one with both a “then” branch and an “else” branch:

  1. if (cond) {
  2. // then branch
  3. }
  4. if (cond) {
  5. // then branch
  6. } else {
  7. // else branch
  8. }

Instead of the block, else can also be followed by another if statement:

  1. if (cond1) {
  2. // ···
  3. } else if (cond2) {
  4. // ···
  5. }
  6. if (cond1) {
  7. // ···
  8. } else if (cond2) {
  9. // ···
  10. } else {
  11. // ···
  12. }

You can continue this chain with more else ifs.

21.2.1. The syntax of if statements

The general syntax of if statements is:

  1. if (cond) «then_statement»
  2. else «else_statement»

So far, the then_statement has always been a block, but you can also use a statement. That statement must be terminated with a semicolon:

  1. if (true) console.log('Yes'); else console.log('No');

That means that else if is not its own construct, it’s simply an if statement whose else_statement is another if statement.

21.3. switch statements

The head of a switch statement looks as follows:

  1. switch switch_expression») {
  2. «switch_body»
  3. }

Inside the body of switch, there are zero or more case clauses:

  1. case «case_expression»:
  2. «statements»

And, optionally, a default clause:

  1. default:
  2. «statements»

A switch is executed as follows:

  • Evaluate the switch expression.
  • Jump to the first case clause whose expression has the same result as the switch expression.
  • If there is no such case clause, jump to the default clause.
  • If there is no default clause, nothing happens.

21.3.1. A first example

Let’s look at an example: The following function converts a number from 1–7 to the name of a weekday.

  1. function dayOfTheWeek(num) {
  2. switch (num) {
  3. case 1:
  4. return 'Monday';
  5. case 2:
  6. return 'Tuesday';
  7. case 3:
  8. return 'Wednesday';
  9. case 4:
  10. return 'Thursday';
  11. case 5:
  12. return 'Friday';
  13. case 6:
  14. return 'Saturday';
  15. case 7:
  16. return 'Sunday';
  17. }
  18. }
  19. assert.equal(dayOfTheWeek(5), 'Friday');

21.3.2. Don’t forget to return or break!

At the end of a case clause, execution continues with the next case clause (unless you return or break). For example:

  1. function dayOfTheWeek(num) {
  2. let name;
  3. switch (num) {
  4. case 1:
  5. name = 'Monday';
  6. case 2:
  7. name = 'Tuesday';
  8. case 3:
  9. name = 'Wednesday';
  10. case 4:
  11. name = 'Thursday';
  12. case 5:
  13. name = 'Friday';
  14. case 6:
  15. name = 'Saturday';
  16. case 7:
  17. name = 'Sunday';
  18. }
  19. return name;
  20. }
  21. assert.equal(dayOfTheWeek(5), 'Sunday'); // not 'Friday'!

That is, the previous implementation of dayOfTheWeek() only worked, because we used return. We can fix this implementation by using break:

  1. function dayOfTheWeek(num) {
  2. let name;
  3. switch (num) {
  4. case 1:
  5. name = 'Monday';
  6. break;
  7. case 2:
  8. name = 'Tuesday';
  9. break;
  10. case 3:
  11. name = 'Wednesday';
  12. break;
  13. case 4:
  14. name = 'Thursday';
  15. break;
  16. case 5:
  17. name = 'Friday';
  18. break;
  19. case 6:
  20. name = 'Saturday';
  21. break;
  22. case 7:
  23. name = 'Sunday';
  24. break;
  25. }
  26. return name;
  27. }
  28. assert.equal(dayOfTheWeek(5), 'Friday');

21.3.3. Empty cases clauses

The statements of a case clause can be omitted, which effectively gives us multiple case expressions per case clause:

  1. function isWeekDay(name) {
  2. switch (name) {
  3. case 'Monday':
  4. case 'Tuesday':
  5. case 'Wednesday':
  6. case 'Thursday':
  7. case 'Friday':
  8. return true;
  9. case 'Saturday':
  10. case 'Sunday':
  11. return false;
  12. }
  13. }
  14. assert.equal(isWeekDay('Wednesday'), true);
  15. assert.equal(isWeekDay('Sunday'), false);

21.3.4. Checking for illegal values via a default clause

A default clause is jumped to if the switch expression has no other match. That makes it useful for error checking:

  1. function isWeekDay(name) {
  2. switch (name) {
  3. case 'Monday':
  4. case 'Tuesday':
  5. case 'Wednesday':
  6. case 'Thursday':
  7. case 'Friday':
  8. return true;
  9. case 'Saturday':
  10. case 'Sunday':
  11. return false;
  12. default:
  13. throw new Error('Illegal value: '+name);
  14. }
  15. }
  16. assert.throws(
  17. () => isWeekDay('January'),
  18. {message: 'Illegal value: January'});

21.4. while loops

A while loop has the following syntax:

  1. while condition») {
  2. «statements»
  3. }

Before each loop iteration, while evaluates condition:

  • If the result is falsy, the loop is finished.
  • If the result is truthy, the while body is executed one more time.

21.4.1. Examples

The following code uses a while loop. In each loop iteration, it removes the first element of arr via .shift() and logs it.

  1. const arr = ['a', 'b', 'c'];
  2. while (arr.length > 0) {
  3. const elem = arr.shift(); // remove first element
  4. console.log(elem);
  5. }
  6. // Output:
  7. // 'a'
  8. // 'b'
  9. // 'c'

If the condition is true then while is an infinite loop:

  1. while (true) {
  2. if (Math.random() === 0) break;
  3. }

21.5. do-while loops

The do-while loop works much like while, but it checks its condition after each loop iteration (not before).

  1. let input;
  2. do {
  3. input = prompt('Enter text:');
  4. } while (input !== ':q');

21.6. for loops

With a for loop, you use the head to control how its body is executed. The head has three parts and each of them is optional:

  1. for initialization»; «condition»; «post_iteration») {
  2. «statements»
  3. }
  • initialization: sets up variables etc. for the loop. Variables declared here via let or const only exist inside the loop.
  • condition: This condition is checked before each loop iteration. If it is falsy, the loop stops.
  • post_iteration: This code is executed after each loop iteration.
    A for loop is therefore roughly equivalent to the following while loop:
  1. «initialization»
  2. while condition») {
  3. «statements»
  4. «post_iteration»
  5. }

21.6.1. Examples

As an example, this is how to count from zero to two via a for loop:

  1. for (let i=0; i<3; i++) {
  2. console.log(i);
  3. }
  4. // Output:
  5. // 0
  6. // 1
  7. // 2

This is how to log the contents of an Array via a for loop:

  1. const arr = ['a', 'b', 'c'];
  2. for (let i=0; i<3; i++) {
  3. console.log(arr[i]);
  4. }
  5. // Output:
  6. // 'a'
  7. // 'b'
  8. // 'c'

If you omit all three parts of the head, you get an infinite loop:

  1. for (;;) {
  2. if (Math.random() === 0) break;
  3. }

21.7. for-of loops

A for-of loop iterates over an iterable – a data container that supports the iteration protocol. Each iterated value is stored in a variable, as specified in the head:

  1. for iteration_variable» of «iterable») {
  2. «statements»
  3. }

The iteration variable is usually created via a variable declaration:

  1. const iterable = ['hello', 'world'];
  2. for (const elem of iterable) {
  3. console.log(elem);
  4. }
  5. // Output:
  6. // 'hello'
  7. // 'world'

But you can also use a (mutable) variable that already exists:

  1. const iterable = ['hello', 'world'];
  2. let elem;
  3. for (elem of iterable) {
  4. console.log(elem);
  5. }

21.7.1. const: for-of vs. for

Note that, in for-of loops, you can use const. The iteration variable can still be different for each iteration (it just can’t change during the iteration). Think of it as a new const declaration being executed each time, in a fresh scope.

In contrast, in for loops, you must declare variables via let or var if their values change.

21.7.2. Iterating over iterables

As mentioned before, for-of works with any iterable object, not just with Arrays. For example, with Sets:

  1. const set = new Set(['hello', 'world']);
  2. for (const elem of set) {
  3. console.log(elem);
  4. }

21.7.3. Iterating over [index, element] pairs of Arrays

Lastly, you can also use for-of to iterate over the [index, element] entries of Arrays:

  1. const arr = ['a', 'b', 'c'];
  2. for (const [index, elem] of arr.entries()) {
  3. console.log(`${index} -> ${elem}`);
  4. }
  5. // Output:
  6. // '0 -> a'
  7. // '1 -> b'
  8. // '2 -> c'

21.8. for-await-of loops

for-await-of is like for-of, but it works with asynchronous iterables instead of synchronous ones. And it can only be used inside async functions and async generators.

  1. for await (const item of asyncIterable) {
  2. // ···
  3. }

for-await-of is described in detail in a later chapter.

21.9. for-in loops (avoid)

for-in has several pitfalls. Therefore, it is usually best to avoid it.

This is an example of using for-in:

  1. function getOwnPropertyNames(obj) {
  2. const result = [];
  3. for (const key in obj) {
  4. if ({}.hasOwnProperty.call(obj, key)) {
  5. result.push(key);
  6. }
  7. }
  8. return result;
  9. }
  10. assert.deepEqual(
  11. getOwnPropertyNames({ a: 1, b:2 }),
  12. ['a', 'b']);
  13. assert.deepEqual(
  14. getOwnPropertyNames(['a', 'b']),
  15. ['0', '1']); // strings!

This is a better alternative:

  1. function getOwnPropertyNames(obj) {
  2. const result = [];
  3. for (const key of Object.keys(obj)) {
  4. result.push(key);
  5. }
  6. return result;
  7. }

For more information on for-in, consult “Speaking JavaScript”.