javascript

Flow control and Conditionals


 

Control flow refers to the sequence in which statements are executed within a program. By default, control flow follows a linear path where statements are processed in the order they appear in the program file, reading from left to right and from top to bottom.

 

The control flow executes from the first line and till the last line, unless and until computer execution goes through conditionals and loops.
 

Some of the conditionals and loops are:

 

1. Conditional Statements (if…else):

These statements allow you to execute different blocks of code based on given conditions.

 

Example:

// Conditional Statements
if (condition) {
    // if condition is true
} else {
    // if condition is false
}

 

2. Switch Stement

It provides a way to execute different code blocks based on different cases.

 

Example:

// Switch Statement
switch (expression) {
    case value1:
        // code to be executed if expression matches value1
        break;
    case value2:
        // code to be executed if expression matches value2
        break;
    default:
        // code to be executed if expression doesn't match any case
}

 

2. Switch Statement:

It provides a way to execute different code blocks based on different cases.

 

Example:

// Loops
for (initialization; condition; increment/decrement) {
    // code to be executed
}

while (condition) {
    // code to be executed
}

do {
    // code to be executed
} while (condition);

 

3. Loops (for, while, do…while):

These structures allow you to execute a block of code repeatedly.

 

Example:

// Loops
for (initialization; condition; increment/decrement) {
    // code to be executed
}

while (condition) {
    // code to be executed
}

do {
    // code to be executed
} while (condition);

 

4. Break and Continue:

These keywords allow you to alter the flow within loops. Break terminates the loop, while continue skips the current iteration and moves to the next.

 

Example:

// Break and Continue
for (let i = 0; i < 5; i++) {
    if (i === 3) {
        break; // terminates the loop when i equals 3
    }
    console.log(i); // will print 0, 1, 2
}

for (let i = 0; i < 5; i++) {
    if (i === 2) {
        continue; // skips the iteration when i equals 2
    }
    console.log(i); // will print 0, 1, 3, 4
}