Dirk Harriman Banner Image


Notes Javascript - Control Flow



Control Flow, Iteration

JavaScript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. Any JavaScript expression is also a statement.

Block Statement

The most basic statement is a block statement, which is used to group statements. The block is delimited by a pair of curly brackets.

{ statement1; statement2; // ... statementN; }

Note: var-declared variables are not block-scoped, but are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. For example:

var x = 1; { var x = 2; } console.log(x); // 2

This outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block.
(In C or Java, the equivalent code would have output 1.)

This scoping effect can be mitigated by using let or const.


If Then Else

This is pretty much the same as it is in the C language.

if (condition) { statement1; } else { statement2; } if (condition1) { statement1; } else if (condition2) { statement2; } else if (conditionN) { statementN; } else { statementLast; }



Note: The break staement is optional. If it is ommited, the control flow will go to the next statement otherwise it will exit the switch statement.

switch (expression) { case label1: statements1; break; case label2: statements2; break; // ... default: statementsDefault; }


For Next

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop.

for (initialization; condition; afterthought) { // statement }

1 The initializing expression initialization, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
2 The condition expression is evaluated. If the value of condition is true, the loop statements execute. Otherwise, the for loop terminates. (If the condition expression is omitted entirely, the condition is assumed to be true.)
3 The statement executes. To execute multiple statements, use a block statement ({ }) to group those statements.
4 If present, the update expression afterthought is executed.
5 Control returns to Step 2.

for (let x = 0; x < 10; x++) { // THE VALUE OF x WILL ITERATE FROM 0 TO 9 }

Example Using A Web Environment

In the example below, the function contains a for statement that counts the number of selected options in a scrolling list (a <select> element that allows multiple selections).


<form name="selectForm"> <label for="musicTypes"> Choose some music types, then click the button below: </label> <select id="musicTypes" name="musicTypes" multiple> <option selected>R&B</option> <option>Jazz</option> <option>Blues</option> <option>New Age</option> <option>Classical</option> <option>Opera</option> </select> <button id="btn" type="button">How many are selected?</button> </form>


Here, the for statement declares the variable i and initializes it to 0. It checks that i is less than the number of options in the <select> element, performs the succeeding if statement, and increments i by 1 after each pass through the loop.

function countSelected(selectObject) { let numberSelected = 0; for (let i = 0; i < selectObject.options.length; i++) { if (selectObject.options[i].selected) { numberSelected++; } } return numberSelected; } const btn = document.getElementById("btn"); btn.addEventListener("click", () => { const musicTypes = document.selectForm.musicTypes; console.log(`You have selected ${countSelected(musicTypes)} option(s).`); });


Do While

The do...while statement repeats until a specified condition evaluates to false.

do { statement } while (condition);


While Do

A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:

while (condition) { statement }


For In

The for...in statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements.
A for...in statement looks as follows:

for (variable in object) { statement }


The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values.

function dumpProps(obj, objName) { let result = ""; for (const i in obj) { result += `${objName}.${i} = ${obj[i]}<br>`; } result += "<hr>"; return result; }

For an object car with properties make and model, result would be:

car.make = Ford car.model = Mustang

For In & Arrays

Note: Although it may be tempting to use this as a way to iterate over Array elements, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes.

Therefore, it is better to use a traditional for loop with a numeric index when iterating over arrays, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the Array object (such as adding custom properties or methods).


For Of

The for...of statement creates a loop Iterating over iterable objects (including Array, Map, Set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

for (variable of object) { statement }

The following example shows the difference between a for...of loop and a for...in loop.
While for...in iterates over property names, for...of iterates over property values:

const arr = [3, 5, 7]; arr.foo = "hello"; for (const i in arr) { console.log(i); } // "0" "1" "2" "foo" for (const i of arr) { console.log(i); } // Logs: 3 5 7

The for...of and for...in statements can also be used with destructuring. For example, you can simultaneously loop over the keys and values of an object using Object.entries().

const obj = { foo: 1, bar: 2 }; for (const [key, val] of Object.entries(obj)) { console.log(key, val); } // "foo" 1 // "bar" 2



A label provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.

The syntax of the labeled statement looks like the following:

label: { statement }

The value of label may be any JavaScript identifier that is not a reserved word.
The statement that you identify with a label may be any statement.



Use the break statement to terminate a loop, switch, or in conjunction with a labeled statement.

The syntax of the break statement looks like this:

break; break label;

1. The first form of the syntax terminates the innermost enclosing loop or switch.
2. The second form of the syntax terminates the specified enclosing labeled statement.
Example 1

The following example iterates through the elements in an array until it finds the index of an element whose value is theValue:

for (let i = 0; i < a.length; i++) { if (a[i] === theValue) { break; } }

Example 2: Breaking to a label

let x = 0; let z = 0; labelCancelLoops: while (true) { console.log("Outer loops: ", x); x += 1; z = 1; while (true) { console.log("Inner loops: ", z); z += 1; if (z === 10 && x === 10) { break labelCancelLoops; } else if (z === 10) { break; } } }



The continue statement can be used to restart a while, do-while, for, or label statement.

The syntax of the continue statement looks like the following:

continue; continue label;

Example 1

The following example shows a while loop with a continue statement that executes when the value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.

let i = 0; let n = 0; while (i < 5) { i++; if (i === 3) { continue; } n += i; console.log(n); } //1,3,7,12

If you comment out the continue;, the loop would run till the end and you would see 1,3,6,10,15.

Example 2

A statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program terminates the current iteration of checkj and begins the next iteration. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is completed, and checkiandj reiterates until its condition returns false. When false is returned, the program continues at the statement following checkiandj.
If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement.

let i = 0; let j = 10; checkiandj: while (i < 4) { console.log(i); i += 1; checkj: while (j > 4) { console.log(j); j -= 1; if (j % 2 === 0) { continue checkj; } console.log(j, " is odd."); } console.log("i = ", i); console.log("j = ", j); }