Control Structure in JavaScript

Control Structure in JavaScript

Hey folks, what's up? after completing data types in JavaScript, I'm going to start writing about control structure in JavaScript. Control structures in JavaScript are fundamental building blocks that control the flow of execution in a program. They include conditionals, loops, and error-handling mechanisms. In this article, we will discuss the if-else statement in JavaScript.

1. Conditional Statements

if-else statement

The if-else statement is used to execute a block of code if a specified condition is true. If the condition is false, another block of code can be executed.

Syntax

The syntax of the if-else statement is as follows:

let age = 18;

if (age >= 18) {
    console.log("You are an adult.");
} else {
    console.log("You are a minor.");
}

In the example above, the if statement checks if the age variable is greater than or equal to 18. If the condition is true, the message "You are an adult." is displayed. Otherwise, the message "You are a minor." is displayed.

Nested if-else Statements

You can also nest if-else statements within each other to handle multiple conditions. Here's an example:

let num = 0;

if (num > 0) {
    console.log("Positive number");
} else if (num < 0) {
    console.log("Negative number");
} else {
    console.log("Zero");
}

In the example above, the program checks if the num variable is greater than 0, less than 0, or equal to 0, and displays the appropriate message based on the condition.

The if-else statement is a powerful tool for controlling the flow of execution in JavaScript programs. It allows you to execute different blocks of code based on specified conditions, making your programs more flexible and responsive.

switch Statement

The switch statement is a control structure that allows you to execute different blocks of code based on the value of a variable. It is similar to the if statement, but it provides a more concise way to handle multiple conditions.

Example:

let day = 3;
let dayName;

switch (day) {
    case 1:
        dayName = 'Monday';
        break;
    case 2:
        dayName = 'Tuesday';
        break;
    case 3:
        dayName = 'Wednesday';
        break;
    case 4:
        dayName = 'Thursday';
        break;
    case 5:
        dayName = 'Friday';
        break;
    case 6:
        dayName = 'Saturday';
        break;
    case 7:
        dayName = 'Sunday';
        break;
    default:
        dayName = 'Invalid day';
}

console.log(dayName); // Outputs: Wednesday

In the example above, the switch statement evaluates the value of the day variable and assigns the corresponding day name to the dayName variable. Since the value of the day is 3, the output is Wednesday.

2. Loops

for Loop:

The for Loop repeats a block of code a specified number of times.

Example:

for (let i = 0; i < 5; i++) {
    console.log(i);
}

// Outputs:
// 0
// 1
// 2
// 3
// 4

In the example above, the for loop iterates over the values of the variable i from 0 to 4 (inclusive) and logs each value to the console.

for...in Loop

The for..in loop iterates over the properties of an object.

Example:

const person = {
    name: 'John',
    age: 30
};

for (let key in person) {
    console.log(key, person[key]);
}

// Outputs:
// name John
// age 30

In the example above, the for...in loop iterates over the keys of the person object and logs each key-value pair to the console.

for...of Loop

The for...of loop iterates over the values of an iterable object(like an array).

Example:

const fruits = ['Apple', 'Banana', 'Cherry'];

for (let fruit of fruits) {
    console.log(fruit);
}

// Outputs:
// Apple
// Banana
// Cherry

In the example above, the for...of loop iterates over the values of the fruits array and logs each value to the console.

while Loop

The while loop repeats a block of code as long as a specified condition is true.

Example:

while (count1 < 5) {
    console.log(count1);
    count1++;
}

// Outputs:
// 0
// 1
// 2
// 3
// 4

In the example above, the while loop repeats the block of code as long as the count variable is less than 5. The count variable is incremented by 1 in each iteration.

do...while Loop

The do...while loop is similar to the while loop, but it executes the block of code once before checking the condition.

Example:

let count = 0;

do {
    console.log(count);
    count++;
} while (count < 5);

// Outputs:
// 0
// 1
// 2
// 3
// 4

In the example above, the do...while loop executes the block of code one before checking the condition. The loop continues to execute as long as the count variable is less than 5.

3. Error handling

Error handling is a mechanism to handle runtime errors such as exceptions, which are thrown by a program.

try-catch statement

The try...catch statement handles exceptions. The try block contains code that might throw an exception. If an exception occurs, the catch block is executed, and the error object contains information about the exception.

Syntax

 try {
    // Code that may throw an exception
 } catch (error) {
     // Code to handle the exception
 }

Example

Let's see an example of error handling in JavaScript:

try {
    let x = 1 / 0; // Division by zero
    console.log(x);
} catch (error) {
    console.log('An error occurred:', error.message);
}
// Outputs: An error occurred: Division by zero

In the example above, the code inside the try block attempts to divide 1 by 0, which results in a division by zero error. The catch block catches the expectation and logs an error message to the console.

try...catch...finally

You can also use the finally blocks to execute cleanup code, which runs regardless of whether an exception occurs or not.

Syntax:

 try {
     // Code that may throw an exception
 } catch (error) {
     // Code to handle the exception
 } finally {
     // Cleanup code
 }

Example:

Let's see an example of error handling with a finally block in JavaScript:

try {
    let x = 1 / 0; // Division by zero
    console.log(x);
} catch (error) {
    console.log('An error occurred:', error.message);
} finally {
    console.log('Cleanup code');
}
// Outputs:
// An error occurred: Division by zero

In the example above, the finally block contains cleanup code that runs regardless of whether an exception occurs or not. The cleanup code is useful for releasing resources or closing connections.

throw statement

You can also throw custom exceptions using the throw statement. This allows you to create your own error messages and handle them in the catch block.

Syntax

The syntax of the throw statement is as follows:

throw new Error('Custom error message');

Let's see an example of throwing a custom exception in JavaScript:

try {
    throw new Error('Custom error message');
}
catch (error) {
    console.log('An error occurred:', error.message);
}
// Outputs: An error occurred: Custom error message

In the example above, the throw statement throws a custom error message, which is caught by the catch block and logged to the console.

4. Break and Continue

Break and continue are used to control the flow of loops.

The break statement is used to exit a loop prematurely, while the continue statement is used to skip the current iteration of a loop and proceed to the next one.

break statement

The break statement is used to exit a loop prematurely. When the break statement is encountered inside a loop, the loop is terminated, and the program continues with the next statement after the loop.

Syntax

break;

Example

Let's see an example of the break statement in JavaScript:

for (let i = 0; i < 5; i++) {
    if (i === 3) {
        break;
    }
    console.log(i);
}
//Outputs:
//
//0
//1
//2

In the example above, the for loop iterates over the values of the variable i from 0 to 4 (inclusive). When the value of i is 3, the break the statement is encountered, and the loop is terminated prematurely.

The continue Statement

The continue statement is used to skip the current iteration of a loop and proceed to the next one. When the continue statement is encountered inside a loop, the current iteration is skipped, and the loop continues with the next iteration.

Syntax

continue;

Example:

Let's see an example of the continue statement in Javascript:

for (let i = 0; i < 5; i++) {
    if (i === 3) {
        continue;
    }
    console.log(i);
}
//Outputs:
//
//0
//1
//2
//4

In the example above, the for loop iterates over the values of the variable i from 0 to 4 (inclusive). When the value of i is 3, the continue statement is encountered, and the current iteration is skipped. The loop continues with the next iteration.

5. Ternary Operator

The ternary operator is a concise way to write conditional statements in JavaScript. It can be used to simplify code and make it more readable by reducing the number of lines needed for simple if-else statements. It is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

Syntax

condition ? expression1 : expression2;

The ternary operator works as follows:

  • The condition is evaluated.

  • If the condition is true, expression1 is executed.

  • If the condition is false, expression2 is executed.

Example:

Let's see an example of the ternary operator in JavaScript:

let age = 18;
let message = age >= 18 ? 'You are an adult.' : 'You are a minor.';
console.log(message);
//Outputs: You are an adult.

In the example above, the ternary operator checks if the age variable is greater than or equal to 18. If the condition is true, the message 'You are an adult.' is assigned to the message variable. Otherwise, the message 'You are a minor.' is assigned to the message variable.

6. Logical Operator

Logical operators are used to combine multiple conditions in JavaScript. There are three logical operators in JavaScript: AND (&&), OR (||), and NOT (!).

The AND (&&) Operator

The AND operator returns true if both operands are true; otherwise, it returns false. The AND operator is represented by two ampersands (&&).

Syntax

operand1 && operand2;

Example:

Let's see an example of the AND operator in JavaScript:

let x = 5;
let y = 10;
let z = 15;

if (x < y && y < z) {
    console.log('Both conditions are true');
} else {
    console.log('At least one condition is false');
}
//Outputs: Both conditions are true

In the example above, the if statement checks if both x is less than y and y is less than z. Since both conditions are true, the message 'Both conditions are true' is displayed.

The OR (||) Operator

The OR operator returns true if at least one of the operands is true; otherwise, it returns false. The OR operator is represented by two vertical bars (||).

Syntax

operand1 || operand2;

Example:

Let's see an example of the OR operator in JavaScript:

let x1 = 5;
let y1 = 10;
let z1 = 15;

if (x1 > y1 || y1 < z) {
    console.log('At least one condition is true');
}
//Outputs: At least one condition is tr

In the example above, the if statement checks if either x is greater than y or y is less than z. Since the second condition is true, the message 'At least one condition is true' is displayed.

The NOT (!) Operator

The NOT operator returns the opposite of the operand. If the operand is true, the NOT operator returns false, and vice versa. The NOT operator is represented by an exclamation mark (!).

Syntax

!operand;

Example:

Let's see an example of the NOT operator in JavaScript:

let x2 = 5;
let y2 = 10;

if (!(x2 > y2)) {
    console.log('x is not greater than y');
}
//Outputs: x is not greater than y

In the example above, the if statement checks if x is not greater than y using the NOT operator. Since the condition is true, the message 'x is not greater than y' is displayed.

Conclusion

Control structures in JavaScript are pivotal for directing the execution flow of a program. They provide the mechanisms for decision-making (conditional statements) and repetitive execution (loops). Mastery of these constructs is essential for writing efficient, readable, and maintainable code. Proper use of control structures can greatly enhance the logic and functionality of JavaScript applications, allowing developers to solve complex problems and implement intricate logic seamlessly.

Happy Learning!