Start learning free

LESSON 119 OF 410 · WHILE LOOPS & FOR LOOPS

While loop: Printing more numbers in JavaScript

Lesson Read the full explanation

Practice makes perfect! Let's check two more examples of printing numbers using the while loop.


Example 1:

Let's print all the even numbers from 4 through 14:

let i = 4;
while(i <= 14) {
	console.log(i);
	i += 2;
}

The output of this program is:

4
6
8
10
12
14

Example 2:

We can also loop in reverse. Let's print all even numbers from 12 to 4 in decreasing order:

let i = 12;
while(i >= 4) {
	console.log(i);
	i -= 2;
}

The output of this program is:

12
10
8
6
4

Assignment
Let's print all the odd numbers from 23 to 7 in decreasing order!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    JAVASCRIPT · WHILE LOOPS & FOR LOOPS

    Printing Numbers 2 in JavaScript, explained

    Introduction

    In this lesson, we will explore the use of the while loop in JavaScript to print sequences of numbers. The while loop is a fundamental control structure that allows code to be executed repeatedly based on a given Boolean condition. Understanding how to use loops effectively is crucial for tasks such as iterating over data structures, automating repetitive tasks, and implementing complex algorithms.

    Understanding the Basics

    The while loop continues to execute a block of code as long as the specified condition evaluates to true. The basic syntax of a while loop is:

    while (condition) {
        // code to be executed
    }
    

    It's important to ensure that the condition will eventually become false; otherwise, the loop will run indefinitely, causing an infinite loop.

    Main Concepts

    Let's break down the key concepts and techniques involved in using the while loop:

    • Initialization: Set up a variable before the loop starts.
    • Condition: The loop will continue to run as long as this condition is true.
    • Update: Modify the variable within the loop to eventually make the condition false.

    In the examples provided, we initialize a variable i, set a condition for the loop, and update i within the loop to print sequences of numbers.

    Examples and Use Cases

    Let's look at the examples provided in the lesson:

    Example 1: Printing Even Numbers from 4 to 14

    let i = 4;
    while (i <= 14) {
        console.log(i);
        i += 2;
    }
    

    This loop starts with i initialized to 4 and prints even numbers up to 14 by incrementing i by 2 in each iteration.

    Example 2: Printing Even Numbers from 12 to 4 in Reverse

    let i = 12;
    while (i >= 4) {
        console.log(i);
        i -= 2;
    }
    

    This loop starts with i initialized to 12 and prints even numbers down to 4 by decrementing i by 2 in each iteration.

    Assignment: Printing Odd Numbers from 23 to 7 in Decreasing Order

    Now, let's solve the assignment:

    let i = 23;
    while (i >= 7) {
        console.log(i);
        i -= 2;
    }
    

    This loop starts with i initialized to 23 and prints odd numbers down to 7 by decrementing i by 2 in each iteration.

    Common Pitfalls and Best Practices

    Here are some common mistakes to avoid and best practices to follow:

    • Infinite Loops: Ensure the loop's condition will eventually become false.
    • Off-by-One Errors: Double-check the loop's start and end conditions to avoid missing or repeating elements.
    • Clear Initialization and Updates: Clearly initialize and update the loop variable to maintain readability and prevent errors.

    Advanced Techniques

    Once you're comfortable with basic loops, you can explore more advanced techniques such as nested loops, using loops with arrays, and combining loops with conditional statements to solve more complex problems.

    Code Implementation

    Here is the complete code for the assignment:

    let i = 23;
    while (i >= 7) {
        console.log(i);
        i -= 2;
    }
    

    This code demonstrates how to use a while loop to print odd numbers from 23 to 7 in decreasing order.

    Debugging and Testing

    When debugging loops, consider the following tips:

    • Print Statements: Use console.log to print the loop variable and check its value at each iteration.
    • Breakpoints: Use breakpoints in your development environment to pause execution and inspect the loop's behavior.
    • Test Cases: Write test cases to verify the loop's output for different input ranges and conditions.

    Thinking and Problem-Solving Tips

    When approaching problems involving loops, consider these strategies:

    • Break Down the Problem: Divide the problem into smaller parts and solve each part step-by-step.
    • Visualize the Loop: Draw a flowchart or write pseudocode to visualize the loop's execution.
    • Practice: Solve various loop-related problems to build confidence and improve your problem-solving skills.

    Conclusion

    In this lesson, we explored the use of the while loop in JavaScript to print sequences of numbers. We covered the basics, examined examples, and discussed best practices and common pitfalls. Mastering loops is essential for efficient programming and problem-solving. Keep practicing and experimenting with different loop scenarios to enhance your skills.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free