# Control structures

# Selection

  • In JavaScript, you can use the following (classical) selection structures

# if

# if - else

# if - else if - else

if (condition1) {
    //  block of code to be executed if condition1 is true
}
else if (condition2) {
    //  block of code to be executed if condition1 is false and condition2 is true
} else if (condition3) {
    //  block of code to be executed if condition1 and condition2 are false and condition3 is true
} else {
    //  block of code to be executed if none of the previous conditions are true
}
1
2
3
4
5
6
7
8
9
10

# switch

switch (expression) {
    case x:
        // block of code to be executed if case x is true
        break;
    case y:
        // block of code to be executed if case y is true
        break;
    default:
        // block of code to be executed if none of the previous cases are true
}
1
2
3
4
5
6
7
8
9
10

WARNING

Don't forget the break at the end of each case!

# Iteration

  • Also the following (classical) iteration structures are available in JavaScript

# for

const end = 10;
for (let i = 0; i <= end; i++) {
  // block of code to be executed
}
1
2
3
4

# while

let i = 0;
const end = 10;
while (i <= end) {
	 // block of code to be executed
	i++;
}
1
2
3
4
5
6

# do while

let i = 0;
const end = 10;
do {
	 // block of code to be executed
	i++;
} while (i <= end) 
1
2
3
4
5
6

REMARK

Ado wile loop always iterates at least one time, even if the condition is false!

# Iterating arrays

  • There are several ways to loop over an array, but the most interesting (and the only one we use in this course) is the forEach (opens new window) iteration
  • The callback function can have three parameters:
    • element: the current element being processed in the array
    • index (optional): the index of the current element
    • array (optional): the full array on which forEach is performed
const array = ['element1', 'element2', 'element3', ...];
array.forEach(function(element, index, array) {
    // block of code to be executed on the current element
})
1
2
3
4

# Examples

# Selection with 'if - else if'

  • Open es6/controls/else_if.html and es6/controls/else_if.js
  • Leave the input field empty or enter a number between 0 and 20 and check if you pass/fail the JavaScript course

# Selection with 'switch'

  • Open es6/controls/switch.html and es6/controls/switch.js
  • In this example, we replaced the numeric field with a range slider
    • This removes the need for an additional test to see if the field is empty

# Compare iteration methods

  • Open es6/controls/drawBlocks.html and es6/controls/drawBlocks.js

# Iterating arrays

Open es6/controls/colorBlocks.html and es6/controls/colorBlocks.js

# Exercises

  • Open exercises/index.html and make the exercises under the tab ES6 > Controls
Last Updated: 4/20/2022, 1:45:58 PM