JavaScript Control Flow🎮🛂

JavaScript Control Flow🎮🛂

Understanding and Implementing Conditional Statements and Loops in JavaScript

JavaScript is a powerful programming language that allows developers to create complex and dynamic web applications. Two important concepts in JavaScript are conditional statements and loops. In this article, we will discuss these concepts in detail and provide examples to illustrate their usage.

Conditional Statement

A conditional statement is a type of control flow statement that allows you to execute different blocks of code based on certain conditions. The most commonly used conditional statement in JavaScript is the if-else statement.

i. if-else

The if-else statement allows you to check if a certain condition is true, and if it is, it will execute a block of code. If the condition is false, it will execute another block of code. The syntax for an if-else statement is as follows:

if (condition) {
    // If the condition is true, run the code
} else {
   // If the condition is false, run the code
}

Here is an example of an if-else statement that checks if a number is positive or negative:

let num = -5;
if (num >= 0) {
    console.log(num + " is a positive number.");
} else {
    console.log(num + " is a negative number.");
}

ii. if-else if- else

JavaScript also supports the else-if statement, which allows you to check multiple conditions in a single if-else statement. The following is the syntax for an else-if statement:

if (condition1) {
    // If the condition1 is true, run the code
} else if (condition2) {
    // If the condition1 is false, and condition2 is true run the code
} else {
    // If the condition1 and condition2 is false, run the code
}

Here is an example of an else-if statement that checks if a number is positive, negative or zero:

let num = 0;
if (num > 0) {
    console.log(num + " is a positive number.");
} else if (num < 0) {
    console.log(num + " is a negative number.");
} else {
    console.log(num + " is zero.");
}

iii. Ternary Operator

JavaScript also supports the ternary operator, which is a shorthand way to write an if-else statement. The syntax for a ternary operator is as follows:

let result = condition ? value1 : value2;

Here is an example of a ternary operator that checks if a number is even or odd:

let num = 5;
let result = (num % 2 == 0) ? "even" : "odd";
console.log(num + " is " + result);

iv. Switch Statement

A switch statement in JavaScript is a control flow statement that allows you to execute different codes depending on the value of an expression. It is an alternative to using a series of if-else statements and can make your code more readable and maintainable.

The basic syntax of a switch statement is as follows:

switch (expression) {
    case value1:
        // code to be executed if expression === value1
        break;
    case value2:
        // code to be executed if expression === value2
        break;
    ...
    default:
        // code to be executed if expression doesn't match any of the cases
}

The expression is evaluated and compared to the values in each case. If a match is found, the code associated with that case is executed. If no match is found, the code in the default case is executed. It is important to note that the break statement is used to exit the switch statement once a case has been matched. If a break statement is not used, the code for the next case will also be executed.

Here is an example of a switch statement in action:

let day = new Date().getDay();

switch (day) {
    case 0:
        console.log("Sunday");
        break;
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    case 3:
        console.log("Wednesday");
        break;
    case 4:
        console.log("Thursday");
        break;
    case 5:
        console.log("Friday");
        break;
    case 6:
        console.log("Saturday");
        break;
    default:
        console.log("Invalid day");
}

In this example, the day variable is assigned the current day of the week. The switch statement compares the day variable to each case, and if a match is found, the corresponding day of the week is logged to the console. If the day variable does not match any of the cases, the default case is executed and "Invalid day" is logged to the console.

One of the benefits of using a switch statement is that it can make your code more readable and maintainable. For example, if you have a large number of conditions to check in an if-else statement, it can become difficult to keep track of which conditions are being checked and what actions are being taken. With a switch statement, the conditions are clearly labeled and the code associated with each condition is grouped. Additionally, a switch statement is faster than an if-else statement in certain cases.

Loops🔄️

A loop is a programming construct that allows code to be executed repeatedly based on a certain condition. JavaScript has several types of loops, including for, for-in, for-of, while and do-while loops.

i. For Loop

To run a piece of code a certain number of times, use for loop. A for loop has the following syntax:

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

Initialization statement execution occurs before the loop starts. The condition is evaluated before each iteration of the loop and if it is true, the code block is executed. Each time the loop is iterated, the increment statement is run. The loop ends when the condition is no longer true.

An illustration of a for loop that counts from 1 to 10 is shown here:

for (let i = 1; i <= 10; i++) {
    console.log(i);
}

ii. For-in Loop

An object's properties are iterated by using a for-in loop. The following is the syntax for a for-in loop:

for (let property in object) {
    console.log(property);
}

Here is an example of a for-in loop that prints the properties of an object:

let person = { name: "Binod", age: 22, job: "student" };
for (let key in person) {
    console.log(key);
}

iii. For-of Loop

A for-of-loop is used to iterate over the elements of an iterable object, such as an array or a string. The syntax for a for-of loop is as follows:

for (let element of iterable) {
    console.log(element);
}

An illustration of a for-of loop that prints an array's elements is shown below:

let colors = ["red", "green", "blue"];
for (let color of colors) {
    console.log(color);
}

iv. While Loop

A while loop is used to execute a block of code repeatedly as long as a certain condition is true. The following is the syntax for a while loop:

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

Here is an example of a while loop that counts from 1 to 10:

let i = 1;
while (i <= 10) {
    console.log(i);
    i++;
}

v. do-while Loop

A do-while loop is similar to a while loop, but with one key difference: the code block within the loop will always execute at least once, regardless of whether the condition is true or false. A do-while loop has the following syntax:

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

As an illustration, consider the following do-while loop, which asks the user for a number and keeps asking until the user submits a value larger than 18:

let num;
do {
    num = prompt("Enter the age above 18:");
} while (num <= 10);
console.log("Thank you for entering a age greater than 18.");

In this example, the code block within the do-while loop prompts the user for a number. The while loop then checks if the number entered is less than or equal to 18. If it is, the loop continues to execute and prompts the user again. If the number entered is greater than 18, the loop stops executing and the message "Thank you for entering a number greater than 18" is printed.

The do-while loop is useful in situations where you want to ensure that a certain block of code is executed at least once, regardless of the outcome of a condition. It can also be useful for input validation, as seen in the example above, where the user is prompted to enter a valid input until the desired condition is met.