Lesson: JavaScript Loops and Conditions

What are Loops in JavaScript?

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.

Types of Loops

What are Conditions in JavaScript?

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.

Example of a `for` Loop

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);
}
            
        

Example of a `while` Loop

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++;
}
            
        

Example of an `if` Condition

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');
}
            
        

Interactive Example

Click the button below to see how loops and conditions work:

Quiz: Test Your Knowledge

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?