COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
JAVASCRIPT | ITERATION
ON THIS PAGE
SECTION 1 | TYPES OF LOOPS
SECTION 2 | THE FOR IN LOOP

SECTION 3 | THE FOR OF LOOP
SECTION 4 | THE WHILE LOOP
SECTION 5 | THE DO WHILE LOOP
SECTION 6 | BREAK AND CONTINUE
SECTION 7 | CODING CONVENTIONS
ALSO IN THIS TOPIC
GETTING STARTED
​VARIABLES & USER INPUT
 OPERATORS
CONDITIONALS (IF STATEMENTS)
YOU ARE HERE | ​ITERATION (LOOPS)
ARRAYS (LISTS)
FUNCTIONS

FURTHER JAVASCRIPT

Picture
WHAT IS ITERATION
In programming, repetition refers to the process of executing the same set of instructions multiple times. Instead of writing out the same code or commands repeatedly, we use structures that allow for a set of instructions to be executed as many times as needed. This concept is fundamental in automating tasks and handling scenarios where operations need to be repeated, such as processing items in a list, performing actions until a certain condition is met, or iterating through datasets.

Loops are essential in programming because they provide a streamlined way to perform repetitive tasks efficiently. Without loops, developers would have to manually write out each iteration of a task, leading to lengthy, redundant, and hard-to-maintain code. With loops, we can simplify complex tasks, reduce potential errors, and make code more readable. They enable programs to handle large amounts of data, respond to user interactions dynamically, and adapt to varying input sizes or conditions, making them a foundational tool in a programmer's toolkit.
SECTION 1 | TYPES OF LOOPS
​As we delve deeper into the realm of loops, it's essential to familiarize ourselves with the different types available. Each type of loop offers unique features suited for specific scenarios. Here's a brief overview of the loops we'll be exploring:

  • for Loop: A classic loop structure, the for loop is versatile and widely used. It's defined by an initializer, a condition, and an iterator, making it perfect for when you know how many times you want to loop.
  • for...in Loop: Tailored for objects, the for...in loop iterates over the enumerable properties of an object, allowing you to process each property's key.
  • for...of Loop: A modern addition to the language, the for...of loop effortlessly iterates over inerrable objects like arrays, strings, and more, directly accessing the values.
  • while Loop: This loop continues executing its block of code as long as its condition remains true. It's especially useful when the number of iterations isn't known beforehand.
  • do...while Loop: A variant of the while loop, the do...while loop guarantees that the loop body will execute at least once, even if the condition is false from the start.

As we progress through each section, we will look at the intricacies of these loops, understanding their syntax, use cases, and best practices.
SECTION 2 | THE FOR LOOP
The for loop is one of the most commonly used loops in JavaScript. It's designed to execute a block of code a specific number of times, making it particularly useful when the number of iterations is known in advance.

THE STRUCTURE
The for loop has a distinct structure that consists of three main parts:
  • Initialization: This is where you set up a loop control variable, often referred to as the "iterator". It's the starting point of your loop.
  • Condition: This tests whether the loop should continue or stop. As long as this condition evaluates to true, the loop will keep running.
  • Iteration: This updates the loop control variable after each loop cycle.

The general syntax is:

for (initialization; condition; iteration) {
    // code to be executed in each loop cycle
}

THE ITERATOR
The iterator is a special variable that controls the number of times the loop will run. It's typically initialized at the start, checked against a condition in each cycle, and updated (either incremented or decremented) after each iteration.

    
In this example:
  • Initialization: We set up an iterator variable i and initialize it to 1.
  • Condition: The loop will continue as long as i is less than or equal to 5.
  • Iteration: After each loop cycle, i is incremented by 1 using i++.
The output will be:
1
2
3
4
5

The for loop provides a concise and structured way to repeat a block of code a specific number of times. The iterator variable plays a crucial role in controlling the loop's behaviour and ensuring it doesn't run indefinitely.

EXAMPLE USE
Suppose we want to generate a multiplication table, we ask the user which tables they would like to see then show them the times table from 1 to 10. We can use a for loop to iterate through numbers 1 to 10 and multiply each by the user input.

Code Editor

    
Test this code in your web browser console to see the result.
SECTION 2 | FOR IN LOOPS
Before we look at FOR IN loops we first need to know about LISTS. In JavaScript, lists are often represented using ARRAYS. An array is an ordered collection of items, where each item can be accessed by its index, for example.

let fruits = ["apple", "banana", "cherry", "date"];

Here, fruits is an array containing four string elements. 'apple' is in index number 0 of this array and 'banana' is in index number 1 of this array and so on. We cover arrays in more detail in the next section but this basic understanding is needed when using FOR IN loops.

    
If you copy and run the code above in your Web Browser Console you will see the following result:

Fruit at index 0 is apple
Fruit at index 1 is banana
Fruit at index 2 is cherry
Fruit at index 3 is date

THE CODE EXPLAINED
​let fruits = ["apple", "banana", "cherry", "date"];
  • This line declares a variable named fruits and assigns it an array containing four string elements. The array represents a list of fruit names.

for (let index in fruits) {
  • This line starts a for...in loop.
  • let index declares a variable named index. Within the context of the for...in loop, this index variable is special. The loop starts with index being 0 (the position of the first element), then 1 (the position of the second element), and so on. Using this iteration we can access each index/position in the array as used on the next line of code.
  • As the loop progresses, the value of index automatically changes (or iterates) through the indices of the fruits array, going from 0 to 3 in this case, since the array has four elements.

console.log("Fruit at index " + index + " is " + fruits[index]);
  • This line is inside the loop and will execute for each iteration.
  • fruits[index] uses the current value of index to access the corresponding fruit in the fruits array. For instance, when index is 0, fruits[0] gives us "apple". When index is 1, fruits[1] gives us "banana", and so on.
  • The entire line displays a message indicating the position (index) of the fruit and its name.

}
  • This line marks the end of the for...in loop. Once all indices of the fruits array have been covered, the loop concludes.

OVERVIEW
  • We have a list of fruits stored in an array.
  • We want to go through each fruit in the list and display its position (index) and name.
  • We use a for...in loop to iterate over the indices (positions) of the array.
  • The index variable automatically takes on each index value in sequence, starting from 0 and going up to the last index of the array (3 in this case).
  • Using the current value of index, we access and display the corresponding fruit from the fruits array.
  • The loop continues until we've gone through all the indices in the fruits array.

EXAMPLE USE
The code demonstrates the use of the for...in loop and if statements in JavaScript. It first presents a list of available fruits to the user. The user is then prompted to select a fruit from the list. Based on the user's selection, the code checks if the chosen fruit is in the list. Finally, it provides feedback to the user, indicating whether or not the selected fruit is available
CORRECT STRUCTURE USED

    
SECTION 3 | FOR OF LOOPS
The for...of loop is a modern addition to JavaScript. It provides a concise way to iterate over inerrable objects, such as arrays, strings, maps, sets, and more. Unlike the for...in loop, which iterates over object properties (or indices in the case of arrays), the for...of loop directly accesses the values of an inerrable object.

for (let value of iterable) {
    // code block to be executed
}
​
  • value: During each iteration, this variable holds the current value from the iterable.
  • iterable: The object you want to iterate over.
Code Editor

    
From the code above you can see the output will be: 
red
green
blue
And the same technique used with a string below

    
From the code above you can see the output will be: 
a
p
p
l
​e
Here, the for...of loop iterates over each character in the string word and prints it.

FOR OF LOOP ADVANTAGES
  • Simplicity: The for...of loop offers a more straightforward syntax for iterating over values compared to traditional for loops or for...in loops.
  • Direct Access: It provides direct access to values without needing to use indices or keys.
  • Flexibility: It can be used with any iterable object, not just arrays.

The for...of loop is a powerful tool in JavaScript, especially when working with iterable objects. It simplifies the process of looping through values, making code more readable and concise. Whether you're working with arrays, strings, or other iterable objects, the for...of loop can be a valuable addition to your coding toolkit
SECTION 4 | THE WHILE LOOP
    The while loop is one of the most fundamental looping constructs in JavaScript. It repeatedly executes a block of code as long as a specified condition evaluates to true. Typically, we set up an initial flag or condition that allows the while loop to start. As the loop progresses, based on certain criteria or conditions within the loop's body, this flag or condition might change, eventually leading to the termination of the loop. This mechanism ensures that the loop doesn't run indefinitely and has a clear exit point.

    while (condition) {
        // code block to be executed
    }
    • condition: Before each iteration, this condition is evaluated. If it returns true, the code inside the loop is executed. If it returns false, the loop terminates.
    Code Editor
    
        
    In this example, the while loop prints numbers from 1 to 5. After each iteration, the value of count is incremented by 1. When count exceeds 5, the condition becomes false, and the loop stops.

    CAUTION OF | Infinite Loops
    One of the potential pitfalls with while loops is the risk of creating an infinite loop. If the condition never evaluates to false, the loop will continue indefinitely, which can cause the program to freeze or crash.

    let value = 1;

    while (value > 0) {
        console.log(value);
    }

    This loop will run endlessly because the condition value > 0 will always be true.

    USED FOR
    • Unknown Iterations: while loops are particularly useful when the number of iterations is unknown in advance, such as reading user input until they provide a valid response.
    • Repetitive Checks: They're great for scenarios where a condition needs to be repeatedly checked, like waiting for a specific resource to become available.

    EXAMPLE USE
    When we ask a user to enter their username we do not know how many times they will enter the incorrect name, for this type of task a WHILE loop is prefect as it will continue to loop until the condition of the correct user name being entered is correct. See the example code below.
    
        
    THE CODE ABOVE
    • We first define the correct username as JohnDoe for this demonstration.
    • We declare a variable enteredUsername to store the username entered by the user.
    • The while loop begins and checks if enteredUsername is not equal to correctUsername. Since enteredUsername is initially undefined, the loop starts.
    • Inside the loop, we use the prompt() function to ask the user for their username.
    • If the entered username is not correct, an alert informs the user that they've entered an incorrect username and prompts them to try again.
    • This process repeats until the user enters the correct username.
    • Once the correct username is entered, the loop terminates, and a welcome message is displayed to the user.

    This example demonstrates how a while loop can be effectively used to validate user input and ensure that the user provides the expected value before proceeding.

    The while loop offers a flexible way to repeat a block of code based on a condition. While it's powerful, it's essential to ensure that the loop's condition will eventually become false to avoid infinite loops. Whether you're performing repetitive tasks, validating input, or waiting for specific conditions, the while loop can be an invaluable tool in your JavaScript repertoire
    SECTION 5 | THE DO WHILE LOOP
    ​The do...while loop is a variant of the while loop. The primary distinction is that the do...while loop guarantees the execution of the loop's body at least once, regardless of the condition. This is because the condition is evaluated after the loop's body has executed.

    do {
        // code block to be executed
    } while (condition);

    ​In the example below, the do...while loop prompts the user to enter a number greater than 10. If the user enters a number 10 or less, they are prompted again. The loop continues until a valid input is provided.
    Code Editor
    
        
    KEY CHARACTERISTICS
    • Guaranteed Execution: The loop's body will always execute at least once, even if the condition is initially false.
    • Post-Check: The condition is checked after the loop's body has executed, determining whether another iteration should occur.

    USER FOR
    • Mandatory User Input: When you want to ensure that a user provides input before checking its validity.
    • Post-Operation Checks: When you perform an operation and then decide whether to repeat it based on the result.

    The do...while loop offers a unique advantage in scenarios where it's essential to execute a block of code at least once before evaluating a condition. By ensuring that the loop's body runs before the condition check, it provides a mechanism for post-operation evaluations and guarantees that certain operations are performed at least once. Whether you're validating user input, performing post-operation checks, or handling scenarios where initial execution is mandatory, the do...while loop can be a valuable tool in your JavaScript coding toolkit.
    SECTION 6 | BREAK AND CONTINUE
    THE BREAK METHOD
    ​The break statement is used to exit or "break out" of a loop or switch statement prematurely. When a break statement is encountered inside a loop, the loop is immediately terminated, and the program continues with the next statement after the loop.
    
        
    The output from the code above would be:
    1
    2
    3
    4

    In this example, the loop is intended to print numbers from 1 to 10. However, when i equals 5, the break statement is executed, and the loop terminates prematurely.

    THE CONTINUE METHOD
    The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. When a continue statement is encountered inside a loop, the current iteration is stopped, and the loop's condition is re-evaluated for the next iteration.
    ​
    ​In a loop, even without the continue statement, the code will naturally progress to the next iteration after executing all the statements within the loop's body. However, there are scenarios where you might want to skip the remaining statements in the current iteration and jump directly to the next iteration based on a specific condition. This is where the continue statement becomes useful.
    
        
    In this first example, the loop checks if i is 3 and prints a different message for it. In the second example, when i is 3, the continue statement is executed, skipping the console.log(i) statement for that iteration. The result would be:

    1
    2
    Three is skipped
    4
    5

    Both break and continue are powerful tools that provide greater control over the flow of loops in JavaScript. The break statement allows for early termination of loops based on specific conditions, while the continue statement enables selective skipping of loop iterations. By understanding and using these statements effectively, developers can write more efficient and flexible code.
    SECTION 7 | CODING CONVENTIONS
    To help you code like a pro in no time here are some good practice tips: 
    • Initialize Variables Properly: Always ensure that loop control variables are initialized correctly. This helps in preventing infinite loops.
    • Limit Infinite Loops: Especially when you're starting, set a maximum number of iterations for your loops to prevent them from running indefinitely.
    • Use Descriptive Variable Names: Instead of using generic names like i or j, use more descriptive names when possible, such as index or itemCount.
    • Avoid Hardcoding Values: Instead of hardcoding values (like the length of an array), use dynamic properties like array.length to make your loops more adaptable to changes.
    • Use for...of for Iterating Over Arrays: When you don't need the index and just the values, for...of is a cleaner way to iterate over arrays.
    • Limit Side Effects: The loop's body should avoid causing side effects that might change the loop's condition unexpectedly.
    • Optimize Loops: If you're working with nested loops, ensure that the innermost loop does the most work to optimize performance.
    • Break Out Early: If you've found what you're looking for or met a certain condition, use the break statement to exit the loop early.

    And here are some common beginner errors to avoid:
    • Infinite Loops: One of the most common mistakes is setting up a loop that never ends. This can happen if the loop's condition always evaluates to true.
    • Off-by-One Errors: This occurs when a loop iterates one time too many or one time too few. It's common when using < instead of <= (or vice versa) in the loop's condition.
    • Not Updating Loop Variables: Forgetting to increment or update the loop control variable can lead to infinite loops.
    • Misusing Loop Types: Using a for loop when a while loop would be more appropriate, or vice versa, can lead to more complex and less readable code.
    • Overusing break and continue: While these can be useful, overusing them can make code harder to read and debug.
    • Modifying the Loop Counter Inside the Loop: Changing the loop counter inside the loop's body can lead to unexpected behaviours.
    • Modifying the Array While Iterating: Adding or removing items from an array while iterating over it can lead to unexpected results.
    • Not Considering Scope: Variables declared inside a loop using let or const have block scope and won't be accessible outside the loop.
    Picture
    TASK 1 | SUM OF MULTIPLES
    OBJECTIVE
    Write a program that calculates the sum of all numbers between 1 and 100 that are multiples of 3 or 5.

    INSTRUCTIONS
    1. Use a for loop to iterate through numbers from 1 to 100.
    2. Within the loop, use a conditional statement to check if the current number is a multiple of 3 or 5.
    3. If the number meets the condition, add it to a running total.
    4. After the loop completes, display the total sum.

    EXAMPLE OUTPUT
    The sum of all multiples of 3 or 5 between 1 and 100 is: 2418


    TASK 2 | PASSWORD RETRY
    OBJECTIVE
    Write a program that prompts the user to enter a password. If the user enters the wrong password, they should be prompted to try again, up to a maximum of 3 attempts.

    INSTRUCTIONS
    1. Set a predefined password (e.g., "JavaScript123").
    2. Use a while loop to give the user up to 3 attempts to enter the correct password.
    3. After each incorrect attempt, inform the user how many attempts they have left.
    4. If the user enters the correct password, display a success message.
    5. If the user fails to enter the correct password after 3 attempts, display an error message.

    EXAMPLE OUTPUT
    Enter your password: wrongpass
    Incorrect! You have 2 attempts left.
    Enter your password: anotherwrong
    Incorrect! You have 1 attempt left.
    Enter your password: JavaScript123
    Success! You've entered the correct password.
    ​
    Picture
    NAVIGATION
    GETTING STARTED
    ​VARIABLES & USER INPUT
     OPERATORS
    CONDITIONALS (IF STATEMENTS)
     ​ITERATION (LOOPS)
    ARRAYS (LISTS)
    FUNCTIONS

    FURTHER JAVASCRIPT
    Picture
    SUGGESTIONS
    We would love to hear from you
    SUBSCRIBE 
    To enjoy more benefits
    We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.