JavaScript Control Structures and Loops

JavaScript Control Structures and Loops

Control Structures: if, else, switch

If-Else Statements

The if 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 using else.

Syntax:

javascriptCopy codeif (condition) {
    // code to be executed if the condition is true
} else {
    // code to be executed if the condition is false
}
Example 1: Basic If-Else Statement

In this example, we check if a person is eligible to vote based on their age.

javascriptCopy codelet age = 20;

if (age >= 18) {
    console.log("You are eligible to vote.");
} else {
    console.log("You are not eligible to vote.");
}
// Output: You are eligible to vote.

Explanation:

  • The if statement checks if age is greater than or equal to 18.

  • Since age is 20, the condition is true, so "You are eligible to vote." is logged into the console.

  • If age were less than 18, the else block would execute, logging "You are not eligible to vote."

Example 2: If-Else with Multiple Conditions

This example assigns a grade based on a score.

javascriptCopy codelet score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}
// Output: Grade: B

Explanation:

  • The code checks multiple conditions using else if.

  • Since score is 85, the condition score >= 80 is true, so "Grade: B" is logged to the console.

  • If none of the conditions were met, the else the block would execute.

Switch Statements

The switch statement is used to perform different actions based on different conditions. It's an alternative to multiple if-else-if statements.

Syntax:

javascriptCopy codeswitch(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 case
}
Example 1: Basic Switch Statement

This example maps a day number to its corresponding day name.

javascriptCopy codelet 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);
// Output: Wednesday

Explanation:

  • The switch statement checks the value of day.

  • When day is 3, the case 3 matches, so dayName is set to "Wednesday".

  • The break statement prevents the code from running into the next case.

Example 2: Switch Statement with Multiple Cases

This example categorizes items into fruits and vegetables.

javascriptCopy codelet fruit = "apple";

switch (fruit) {
    case "banana":
    case "apple":
    case "orange":
        console.log("This is a fruit.");
        break;
    case "carrot":
    case "broccoli":
        console.log("This is a vegetable.");
        break;
    default:
        console.log("Unknown food item.");
}
// Output: This is a fruit.

Explanation:

  • The switch statement checks the value of fruit.

  • The cases for "banana", "apple", and "orange" all execute the same block of code, so "This is a fruit." is logged to the console.

  • The break the statement is used to prevent a fall-through to the next case.

Loops: for, while, do-while

For Loop

The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement.

Syntax:

javascriptCopy codefor (initialization; condition; increment) {
    // code to be executed
}
Example 1: Basic For Loop

This example iterates from 0 to 4 and logs the iteration number.

javascriptCopy codefor (let i = 0; i < 5; i++) {
    console.log("Iteration number " + i);
}
// Output: 
// Iteration number 0
// Iteration number 1
// Iteration number 2
// Iteration number 3
// Iteration number 4

Explanation:

  • The loop starts with i initialized to 0.

  • The condition i < 5 is checked before each iteration.

  • The value of i is incremented by 1 after each iteration.

Example 2: For Loop with an Array

This example iterates over an array of fruits and logs each fruit.

javascriptCopy codelet fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}
// Output:
// apple
// banana
// cherry

Explanation:

  • The loop iterates over the fruits array.

  • The condition i < fruits.length ensures the loop runs for each element in the array.

While Loop

The while loop is used when the number of iterations is not known beforehand. It runs as long as the specified condition is true.

Syntax:

javascriptCopy codewhile (condition) {
    // code to be executed
}
Example 1: Basic While Loop

This example logs numbers from 0 to 4.

javascriptCopy codelet count = 0;

while (count < 5) {
    console.log("Count is " + count);
    count++;
}
// Output:
// Count is 0
// Count is 1
// Count is 2
// Count is 3
// Count is 4

Explanation:

  • The loop continues as long as count is less than 5.

  • count is incremented by 1 after each iteration.

Example 2: While Loop with User Input

This example prompts the user to enter a password until it matches the correct one.

javascriptCopy codelet password = "secret";
let userInput;

while (userInput !== password) {
    userInput = prompt("Enter the password:");
}

console.log("Access granted.");

Explanation:

  • The loop continues until the user enters the correct password.

  • The prompt function is used to get user input.

Do-While Loop

The do-while loop is similar to the while loop, but it guarantees at least one iteration.

Syntax:

javascriptCopy codedo {
    // code to be executed
} while (condition);
Example 1: Basic Do-While Loop

This example logs numbers from 0 to 4.

javascriptCopy codelet num = 0;

do {
    console.log("Number is " + num);
    num++;
} while (num < 5);
// Output:
// Number is 0
// Number is 1
// Number is 2
// Number is 3
// Number is 4

Explanation:

  • The loop runs at least once before the condition num < 5 is checked.

  • num is incremented by 1 after each iteration.

Example 2: Do-While Loop with User Input

This example prompts the user to guess a number until it matches the target number.

javascriptCopy codelet guess;
let target = 7;

do {
    guess = prompt("Guess the number (1-10):");
} while (parseInt(guess) !== target);

console.log("Correct guess!");

Explanation:

  • The loop continues until the user guesses the correct number.

  • The parseInt function is used to convert the user input to an integer.

Did you find this article valuable?

Support Saurabh Mehare by becoming a sponsor. Any amount is appreciated!