# 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

# switch

A switch is a different way to write a long if-else if-else statement.

By writing code this way, you create a more structured and readable if-else if-else.

You "switch" on a variable and define the different "cases" what the value could be. In the end you always provide a "default" case to catch anything that isn't covered in the cases.

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 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
Last Updated: 2/3/2024, 12:49:34 AM