Lädt...


🔧 Using Conditional Statements and Loops in JavaScript


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

JavaScript, like all programming languages, provides tools that allow developers to control the flow of a program. These tools come in the form of conditional statements and loops, which help a program make decisions and repeat actions based on conditions or input. Mastering these control flow mechanisms is essential for building dynamic, interactive web applications.

In this article, we’ll explore how to use conditional statements and loops in JavaScript to manage the flow of your code.

Conditional Statements

Conditional statements allow your JavaScript code to make decisions and execute different blocks of code based on whether certain conditions are true or false. These decisions help you create interactive programs that respond to user inputs, data, or other conditions.

1. if Statement

The if statement is the most basic form of conditional logic. It executes a block of code if the specified condition is true.

let age = 18;

if (age >= 18) {
  console.log("You are eligible to vote.");
}

In the example above, the condition checks if age is greater than or equal to 18. If it is, the message "You are eligible to vote" will be printed to the console.

2. if-else Statement

The if-else statement provides an alternative block of code to execute if the condition is false.

let age = 16;

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

Here, if the condition age >= 18 is false, the code inside the else block will be executed instead.

3. else-if Statement

The else-if statement allows you to check multiple conditions in sequence. If the first condition is false, it moves on to check the next condition, and so on.

let score = 85;

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

In this example, the program checks each condition in order and executes the first block of code where the condition evaluates to true. If none of the conditions are true, the else block is executed.

4. switch Statement

The switch statement is another way to perform conditional logic, especially when you have multiple possible values for a single variable. It compares a variable to several case values and executes the code that matches the case.

let day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start of the week!");
    break;
  case "Wednesday":
    console.log("Midweek day.");
    break;
  case "Friday":
    console.log("Weekend is near.");
    break;
  default:
    console.log("Just another day.");
}

Here, the switch statement checks the value of day. If it matches "Monday", "Wednesday", or "Friday", the corresponding message will be logged. The default case handles any other values not specified in the switch.

Loops

Loops allow you to repeat blocks of code until certain conditions are met. They are particularly useful when you want to perform an action multiple times, such as processing elements in an array or repeatedly checking a condition.

1. for Loop

The for loop is one of the most commonly used loops in JavaScript. It allows you to run a block of code a specific number of times.

for (let i = 0; i < 5; i++) {
  console.log("Iteration number:", i);
}

In this example, the for loop runs five times, logging the current iteration number to the console. The loop consists of three parts:

  1. Initialization (let i = 0): Sets up the loop variable.
  2. Condition (i < 5): Specifies the condition that must be true for the loop to continue.
  3. Increment (i++): Increases the loop variable after each iteration.

2. while Loop

The while loop continues executing a block of code as long as the condition remains true.

let count = 0;

while (count < 5) {
  console.log("Count is:", count);
  count++;
}

In this example, the while loop repeats the code inside it until the condition count < 5 becomes false. Each time the loop runs, count is incremented by one.

3. do-while Loop

The do-while loop is similar to the while loop, except that it guarantees the loop will run at least once. The condition is checked after the loop body is executed.

let number = 5;

do {
  console.log("The number is:", number);
  number++;
} while (number < 10);

In this case, the code inside the do block runs first, and then the condition is checked. If the condition is true, the loop continues to execute.

4. forEach Loop

The forEach loop is specifically designed for iterating over arrays. It executes a function for each element in the array.

let fruits = ["Apple", "Banana", "Cherry"];

fruits.forEach(function (fruit) {
  console.log(fruit);
});

In this example, forEach goes through each element in the fruits array and logs it to the console.

Combining Conditional Statements and Loops

Often in JavaScript, you'll need to combine conditional statements and loops to create more complex logic. For example, you might want to iterate over an array and perform a conditional check on each item.

let numbers = [5, 10, 15, 20, 25];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    console.log(numbers[i] + " is even.");
  } else {
    console.log(numbers[i] + " is odd.");
  }
}

In this example, a for loop iterates over the numbers array. Inside the loop, an if-else statement checks whether each number is even or odd, and prints the result.

Conclusion

Control flow is essential in JavaScript programming as it allows developers to make decisions and execute code conditionally or repeatedly. Conditional statements like if, else, and switch enable programs to make decisions based on the data they encounter, while loops like for, while, and forEach allow for repeated execution of code.

By mastering control flow, you can write more dynamic, responsive, and interactive applications, leading to more robust web development. Understanding when and how to use these tools is a key part of becoming a proficient JavaScript developer.

...

🔧 Loops: For Loops, While Loops, For...Of Loops, For...In Loops


📈 76.28 Punkte
🔧 Programmierung

🔧 Using Conditional Statements and Loops in JavaScript


📈 58.17 Punkte
🔧 Programmierung

🔧 🎓 Mastering JavaScript Basics: Conditional Statements and Loops 🔄


📈 54.1 Punkte
🔧 Programmierung

🔧 Advanced Programming Techniques: Integrating Conditional Statements and Loops


📈 48.41 Punkte
🔧 Programmierung

🔧 Mastering Loops and Conditional Statements in C Programming


📈 48.41 Punkte
🔧 Programmierung

🔧 Control Flow: Mastering Conditional Statements and Loops


📈 48.41 Punkte
🔧 Programmierung

🔧 Use an Object Literal, Better than Using Conditional Statements in JavaScript


📈 41.6 Punkte
🔧 Programmierung

🔧 Conditional Statements in JavaScript: If-Else


📈 37.53 Punkte
🔧 Programmierung

🔧 Conditional Statements in JavaScript: Switch


📈 37.53 Punkte
🔧 Programmierung

🔧 Understanding Conditional Statements in JavaScript


📈 37.53 Punkte
🔧 Programmierung

🔧 **Mastering the Art of Loops in JavaScript: The Complete Guide to For Loops** 🔄✨


📈 36.2 Punkte
🔧 Programmierung

🔧 How to Use Conditional Statements in Python – Examples of if, else, and elif


📈 33.16 Punkte
🔧 Programmierung

🔧 How to Use Conditional Statements in C#: If, Switch, and More Explained with Example Code


📈 33.16 Punkte
🔧 Programmierung

🔧 Go Beginners Series: Control Flow Statements: If-else, Switch, and Loops


📈 32.76 Punkte
🔧 Programmierung

📰 5 Ways to Apply If-Else Conditional Statements in Pandas


📈 31.84 Punkte
🔧 AI Nachrichten

🎥 What are Conditional Statements in Bash? [15 of 20] | Bash for Beginners


📈 31.84 Punkte
🎥 Video | Youtube

🐧 How to Use Conditional Statements in C Programming


📈 31.84 Punkte
🐧 Linux Tipps

📰 Rust Basics Series #6: Conditional Statements


📈 31.84 Punkte
🐧 Unix Server

🔧 Conditional Statements in Python


📈 31.84 Punkte
🔧 Programmierung

🔧 Mastering Python Conditional Statements: A Comprehensive Guide


📈 31.84 Punkte
🔧 Programmierung

🔧 Learning Conditional Statements in Python


📈 31.84 Punkte
🔧 Programmierung

🔧 Practical Guide to Python Conditional Statements


📈 31.84 Punkte
🔧 Programmierung

🔧 Conditional Control Statements in Python


📈 31.84 Punkte
🔧 Programmierung

🔧 The Wisdom of Avoiding Conditional Statements


📈 31.84 Punkte
🔧 Programmierung

🔧 Understanding Conditional Statements in Python


📈 31.84 Punkte
🔧 Programmierung

📰 Conditional Variational Autoencoders with Learnable Conditional Embeddings


📈 31.3 Punkte
🔧 AI Nachrichten

🔧 Enhanced For Loops in Java – How to Use ForEach Loops on Arrays


📈 30.51 Punkte
🔧 Programmierung

🔧 JavaScript if Statements, Equality and Truthy/Falsy – Explained with Examples


📈 23.19 Punkte
🔧 Programmierung

🔧 Understanding if, else, and else if statements in JavaScript


📈 23.19 Punkte
🔧 Programmierung

🔧 If, Else, Else If, and Switch JavaScript Conditional Statement


📈 22.65 Punkte
🔧 Programmierung

🔧 Conditional Branching in JavaScript: `if`, `else`, and `?`


📈 22.65 Punkte
🔧 Programmierung

🔧 Mastering the Conditional React Hooks Pattern (With JavaScript and TypeScript Examples) 🚀


📈 22.65 Punkte
🔧 Programmierung

🔧 JavaScript Operators, Loops, and Flow Control: A Comprehensive Guide


📈 22.25 Punkte
🔧 Programmierung

🔧 🎮Leveling Up with JavaScript: Operators, Conditionals and Loops🕹️


📈 22.25 Punkte
🔧 Programmierung

matomo