Explain how JavaScript can control program execution using conditional statements and loops. Provide code examples.
JavaScript controls program execution using conditional statements and loops, which allow developers to create dynamic and interactive applications. Here's an overview of both.
### Conditional Statements
Conditional statements allow the execution of certain blocks of code based on specified conditions. The primary conditional statements in JavaScript are `if`, `else if`, `else`, and `switch`.
#### Example of `if` Statement
```javascript
let temperature = 30;
if (temperature > 25) {
console.log("It's a hot day!");
} else {
console.log("It's a nice day.");
}
```
In this example:
- If the `temperature` is greater than 25, it will log "It's a hot day!".
- Otherwise, it will log "It's a nice day.".
#### Example of `switch` Statement
```javascript
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;
default:
dayName = "Weekday not recognized";
}
console.log(dayName); // Output: Wednesday
```
In this example:
- The `switch` statement tests the value of `day`.
- Depending on its value, it assigns a corresponding day name to `dayName`.
### Loops
Loops allow for repeating a block of code a certain number of times or until a certain condition is met. The most common types of loops in JavaScript are `for`, `while`, and `do...while`.
#### Example of `for` Loop
```javascript
for (let i = 0; i < 5; i++) {
console.log("Iteration #" + i);
}
```
In this example:
- The `for` loop runs 5 times, printing "Iteration #0", "Iteration #1", up to "Iteration #4".
#### Example of `while` Loop
```javascript
let count = 0;
while (count < 5) {
console.log("Count is: " + count);
count++;
}
```
In this example:
- The `while` loop continues as long as `count` is less than 5, printing the current value of `count` at each iteration.
#### Example of `do...while` Loop
```javascript
let number = 0;
do {
console.log("Number is: " + number);
number++;
} while (number < 5);
```
In this example:
- The `do...while` loop runs at least once, printing the value of `number` and then checking if it is less than 5 to decide whether to continue.
### Summary
Conditional statements allow the program to branch based on conditions, providing a way to execute code selectively. Loops provide repetition, enabling you to run a block of code multiple times without duplicating it. Together, they are fundamental to controlling flow in JavaScript applications, facilitating decision-making and repetitive tasks dynamically.