본문 바로가기
Web/JavaScript

[JavaScript] Control Flow Statements

by llHoYall 2022. 6. 22.

Conditional Statements

if ... else statement

JS's if/else statement is similar to other programming languages.

if (conditions_1) {
  statements_1
} else if (conditions_2) {
  statements_2
} else {
  statements_last
}

If the conditions_1 is true, the statements_1 is executed, and if the conditions_1 is false and conditions_2 is true, the statements_2 is executed. Lastly, all conditions are false, the statements_last is executed.

 

This is so easy topic that doesn't need an explanation, so let's just look at a simple example and move on to the next topic.

const score = 80;
if (score > 70) {
  console.log('pass');
} else {
  console.log('fail');
}
// pass

switch statement

The switch statement is used when you need to execute a statement within many conditional statements.

switch (expression) {
  case label_1:
    statements_1
    [break;]
  case label_2:
    statements_2
    [break;]
  ...
  default:
    statements_def
    [break;]
}

If the expression is matched with the label, the corresponding statements are executed.

There is a break statement in the syntax. It can be used with a conditional statement or a loop statement. If the interpreter encounters the break statement, it stops executing the remaining statements.

We can use these characteristics to create intentional fallthroughs.

And break statement of the default case can be omitted.

 

This is a simple example.

const fruit = 'banana';
switch (fruit) {
  case 'apple':
    console.log('It is a 0.5 dollar.');
    break;
  case 'banana':
    console.log('It is a 1 dollar.');
    break;
  case 'cherry':
    console.log('It is a 10 dollars.');
    break;
  default:
    console.log(`There is no ${fruit}`);
}
// It is a 1 dollar.

const day = 'Mon';
switch (day) {
  case 'Mon':
  case 'Tue':
  case 'Wed':
  case 'Thu':
  case 'Fri':
    console.log('It is a weekday.');
    break;
  case 'Sat':
  case 'Sun':
    console.log('It is a weekend.');
    break;
  default:
    console.log('Error: wrong input');
}
// It is a weekday.

The example will find and print a label that matches a fruit variable. Next, it faces the break statement, so it exits the switch statement.

Please, change the value of the variable fruit.

Loop Statements

for statement

The for statement is usually used when we know the number of iterations.

for ([initialization]; [condition]; [final-expression]) {
  statements
}

This example counts 0 to 9 except even numbers.

for (let i = 0; i < 10; ++i) {
  if (i % 2 === 0) {
    continue;
  }
  console.log(`${i}`);
}

//=> Result
// 1
// 3
// 5
// 7
// 9

The continue statement is used with a loop statement.

If the interpreter encounters this statement, it stops executing the remaining code and goes to the next iteration.

Therefore in this example, if the variable i is an even number, it will encounter the continue statement and goes to the next iteration without printing its value.

while statement

The while statement is repeated until the conditions are not met.

while (conditions) {
  statements
}

This example counts from 0 to 9, but if it faces the number 5, it stops counting.

let count = 0;
while (count < 10) {
  if (count === 5) {
    break;
  }
  console.log(`${count}`);
  count++;
}
// 0
// 1
// 2
// 3
// 4

do ... while statement

The while statement is never executed unless the conditions are met.

In contrast, the do ... while statement runs first and checks conditions, so it runs unconditionally at least once.

do {
  statements
} while (conditions);

This example counts down from the number 3.

let countDown = 3;
do {
  console.log(`${countDown}`);  
} while (--countDown);
// 3
// 2
// 1

Iteration Statements

for .... in statement

The for ... in statement iterates a specified variable over all the enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

for (variable in object) {
  statements
}

Here is an example.

const obj_var = { width: 30, height: 20 };
for (let elem in obj_var) {
  console.log(`${elem}: ${obj_var[elem]}`);
}
// width: 30
// height: 20

for ... of statement

The for ... of statement creates a loop iterating over iterable objects, including built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

for (variable of object) {
  statements
}

Here are some examples.

const var1 = [1, 2, 3];
for (let elem of var1) {
  console.log(`${elem}`);
}
// 1
// 2
// 3

const var2 = 'hello';
for (let elem of var2) {
  console.log(`${elem}`);
}
// h
// e
// l
// l
// o

'Web > JavaScript' 카테고리의 다른 글

[JavaScript] Object  (0) 2022.06.26
[JavaScript] Function  (0) 2022.06.25
[JavaScript] Operators  (0) 2022.06.21
[JavaScript] Data Types  (0) 2022.06.19
[JavaScript] Variable  (0) 2022.06.18

댓글