Quick Explanation: use a `while` loop in JavaScript when the number of iterations is unknown and a `for` loop when the iterations are predetermined. Looping statements are for repeating actions, while selection statements decide which code path to follow based on conditions.
For a more detailed answer ...
When to Use a While Loop vs. a For Loop in JavaScript
While Loop:
Use a `while` loop when you do not know how many times the loop should run. A `while` loop continues executing once a specified condition is considered true.
Example: If you are prompting a user for input until they type "exit," a `while` loop is appropriate because you don't know how many inputs the user will provide (how many times the user will input an answer that is not "exit").
let userInput = "";
while (userInput !== "exit") {
userInput = prompt("Enter something (type 'exit' to quit): ");
console.log(`You entered: ${userInput}`);
}
For Loop:
A `for` loop is ideal for situations where the number of iterations is predetermined, such as looping through each item in an array.
Example: A' for' loop is appropriate if you want to log each element of an array since you know the length.
const items = ["apple", "banana", "cherry"];
for (let i = 0; i < items.length; i++){
console.log(items[i]);
}
```
The for loop will iterate over "items" for the entire length (3). Each element (a fruit name) will be displayed
Output:
"apple"
"banana"
"cherry"
```
Difference Between Looping and Selection Statements
Looping Statements:
Looping statements (like `while` and `for`) execute a block of code multiple times as long as a specified condition is met or until a sequence is exhausted. They are used when you need to repeat the same operation multiple times.
Selection Statements:
Selection statements (like `if`, `else if`, and `else`) allow the code to make decisions and execute specific blocks of code based on conditions. They are used to choose between different code paths depending on whether a condition evaluates to true or false.
Example of Selection Statement in JavaScript:
let temperature = 75;
if (temperature > 80) {
console.log("It's hot outside.");
} else if (temperature > 60) {
console.log("It's warm outside.");
} else {
console.log("It's cold outside.");
}
```
Output: "It's warm outside."
Why:
75 is less than 80, so the "if" statement is fails, to the code moves to the "else if" statement.
The "else if" statement is true (75 is greater than 60), so the code stops and prints "It's warm outside."
Because the code stoped at the "else if" statement, it does not proceed to the "else" statement
In summary, use a `while` loop in JavaScript when the number of iterations is unknown and a `for` loop when the iterations are predetermined. Looping statements are for repeating actions, while selection statements decide which code path to follow based on conditions.