A loop is used to repeat a block of code multiple times. JavaScript provides several types of loops: `for`, `while`, and `do...while`. Loops help automate repetitive tasks in programming.
Conditions are used to perform different actions based on different scenarios. JavaScript uses the `if` statement to check a condition and run the appropriate block of code based on whether the condition is true or false.
This is an example of a `for` loop that runs 5 times and logs the current iteration to the console:
for (let i = 1; i <= 5; i++) {
console.log('Iteration ' + i);
}
This is an example of a `while` loop that continues to run as long as a variable is less than 5:
let i = 1;
while (i <= 5) {
console.log('Iteration ' + i);
i++;
}
This is an example of an `if` condition checking if a number is positive or negative:
let num = -5;
if (num > 0) {
console.log('The number is positive');
} else {
console.log('The number is negative');
}
Click the button below to see how loops and conditions work:
1. What is the purpose of a loop in JavaScript?
2. Which loop would you use when you know the number of iterations in advance?
3. What does the `if` condition do in JavaScript?