Skip to main content

Command Palette

Search for a command to run...

Conditional Statements and loops

Published
6 min readView as Markdown
B

Student | Tech enthusiast | Aspiring software developer

Conditional Statements


Conditional statements are used to perform different actions based on different conditions. In JavaScript, the most common conditional statements are if, else if, and else.

1. if Statement

The if statement is used to specify a block of code that will be executed if a specified condition is true.

if (condition) {
  // code to be executed if the condition is true
}

Example

let age = 18;

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

In this example, the message "You are an adult." will be printed to the console if age is greater than or equal to 18.

2. else Statement

The else statement specifies a block of code to be executed if the same condition is false.

if (condition) {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

For example:

let age = 16;

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

3. else if Statement

The else if statement specifies a new condition to test if the first condition is false.

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else {
  // code to be executed if both condition1 and condition2 are false
}

Example:

let score = 85;

if (score >= 90) {
  console.log("You got an A.");
} else if (score >= 80) {
  console.log("You got a B.");
} else {
  console.log("You need to study more.");
}

practical example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Voting Eligibility Checker</title>
</head>
<body>
  <h1>Voting Eligibility Checker</h1>
  <script src="script.js"></script>
</body>
</html>
// Ask the user for their age
let age = prompt("Enter your age:");

// Convert the input to a number
†i

// Check if the user is eligible to vote
if (age >= 18) {
  console.log("You are eligible to vote!");
  document.write("<p>You are eligible to vote!</p>");
} else {
  console.log("You are not eligible to vote yet.");
  document.write("<p>You are not eligible to vote yet.</p>");
}

While Loop


Let's break down and analyze the given code snippets, focusing on the repetition and the use of loops.

Before Using the Loop

print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")

In this snippet, the same line of code print("Bisesh Adhikari") is repeated multiple times. Specifically, it is repeated nine times. This approach works but is not efficient or scalable, especially if you need to print the same statement many times.

After Using the Loop

let count = 0;
while(count <= 10) { 
    print("Bisesh Adhikari");
    count++;
}

Here, a loop is introduced to handle the repetition.

Explanation:

  1. Initialization: let count = 0;

    • A variable count is initialized to 0.
  2. Condition: while(count <= 10)

    • The while loop will run as long as the condition count <= 10 is true. Since count starts at 0 and goes up to 10, the loop will execute 11 times (from 0 to 10 inclusive).
  3. Body of the Loop:

    • print("Bisesh Adhikari");

      • The statement print("Bisesh Adhikari"); will be executed in each iteration of the loop.
    • count++;

      • After printing, the count variable is incremented by 1.

Comparison

  • Before Using the Loop:

    • Code is longer and repetitive.

    • Not efficient for a larger number of repetitions.

    • Harder to maintain and prone to errors if the number of repetitions needs to change.

  • After Using the Loop:

    • Code is shorter and more readable.

    • Efficient and scalable.

    • Easier to maintain; changing the number of repetitions requires only a single change in the loop condition.

In summary, using a loop to handle repetitive tasks makes the code more efficient, readable, and maintainable. In this case, the while loop is used to print the string "Bisesh Adhikari" 11 times, which is more concise and easier to manage than writing the print statement multiple times manually.

do while loop


General Explanation of a do...while Loop

In general terms, a do...while loop is a type of loop that ensures the block of code inside the loop is executed at least once before the condition is tested. This is useful when you want the code to run at least one time regardless of the condition.

Explanation of a do...while Loop in JavaScript

In JavaScript, a do...while loop is used to execute a block of code at least once and then continue to execute it as long as a specified condition evaluates to true. The condition is checked after the code block has been executed.

Syntax

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

Example

Let's see a practical example of how a do...while loop works in JavaScript:

let count = 0;
do {
    console.log("Bisesh Adhikari");
    count++;
} while (count < 5);

Explanation of the Example

  1. Initialization:

    • let count = 0;

      • A variable count is initialized to 0.
  2. Loop Execution:

    • The code block inside the do section (console.log("Bisesh Adhikari"); count++;) is executed first, regardless of the condition.

    • This means "Bisesh Adhikari" will be printed, and count will be incremented by 1.

  3. Condition Check:

    • After executing the code block, the condition count < 5 is checked.

    • If the condition is true, the loop will execute the code block again.

    • This process repeats until the condition evaluates to false.

For loop


General Explanation of a for Loop

A for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It is commonly used when the number of iterations is known before entering the loop.

Explanation of a for Loop in JavaScript

In JavaScript, a for loop repeats a block of code a specified number of times. It consists of three parts: initialization, condition, and increment/decrement.

Example

Let's see a practical example of how a for loop works in JavaScript:

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

Explanation of the Example

  1. Initialization:

    • let i = 0;

      • A variable i is initialized to 0. This is executed once at the start of the loop.
  2. Condition:

    • i < 5;

      • The loop runs as long as this condition is true. If i is less than 5, the loop continues.
  3. Increment/Decrement:

    • i++

      • After each iteration of the loop, i is incremented by 1.
  4. Code Block:

    • console.log("Bisesh Adhikari");

      • This code block is executed each time the loop runs.

Using a for Loop with an Array

A for loop is often used to iterate over the elements of an array. Here's how you can do it:

Example with Array

const names = ["Bisesh", "Adhikari", "John", "Doe"];
for (let i = 0; i < names.length; i++) {
    console.log(names[i]);
}

Explanation of the Example

  1. Initialization:

    • let i = 0;

      • A variable i is initialized to 0.
  2. Condition:

    • i < names.length;

      • The loop runs as long as i is less than the length of the names array.
  3. Increment/Decrement:

    • i++

      • After each iteration, i is incremented by 1.
  4. Code Block:

    • console.log(names[i]);

      • This code block logs the current element of the array names to the console.

Summary

  • for Loop: Used when the number of iterations is known.

  • Syntax: Includes initialization, condition, and increment/decrement.

  • Array Iteration: The for loop is commonly used to iterate over arrays by using the array's length in the condition.

More from this blog

Bisesh's Blog

24 posts