Loops

Index

In JavaScript, loops are control structures that allow you to repeat a block of code multiple times. They are essential for automating repetitive tasks and processing lists of data. JavaScript offers several types of loops: the loop forthe loop while and the loop do-while. Let's explore each of them:

For Loop

Loop for: The loop for is useful when you know the exact number of times you want a block of code to be repeated. The basic structure is as follows:

				
					for (initialization; condition; increment/decrement) {
  // Block of code to repeat
}
				
			
  • initialization: Here you set the initial value of the variable that will control the loop.
  • conditionThe condition that is evaluated in each iteration. If the condition is truethe loop continues; if it is falsethe loop stops.
  • increase/decreaseThis part is executed after each iteration and is generally used to update the value of the control variable.

Example of a loop for:

				
					for (let i = 0; i < 5; i++) {
  console.log(i); // Will print numbers from 0 to 4.
}
				
			

Loop while

Loop while: The loop while is repeated as long as a condition is true. The structure is as follows:

				
					while (condition) {
  // Block of code to repeat
}
				
			

Example of a loop while:

				
					let counter = 0;
while (counter < 5) {
  console.log(counter); // Print numbers from 0 to 4
  counter++;
}
				
			

do-while loop

Loop do-while: The loop do-while is similar to whilebut ensures that the code block is executed at least once, since the condition is evaluated after the first execution. The structure is as follows:

				
					do {
  // Block of code to repeat
} while (condition);
				
			

Example of a loop do-while:

				
					let x = 0;
do {
  console.log(x); // It will print 0 and then increment
  x++;
} while (x < 3);
				
			

Examples:

Using loops to display a wave of patterns on the console

				
					let counter = "1";
let line = "";
console.log("@");
while (counter <= 10) {
  line += "|";
  counter++;
  console.log(line);
}
				
			

The code uses a loop while to build a series of lines with vertical bars. Let's see step by step what it does:

				
					let counter = "1"; // Initialize the variable 'counter' with the string value "1".
let line = ""; // The variable 'line' is initialized as an empty string.
console.log("@"); // The "@" character is printed to the console.

while (counter <= 10) {
  line += "|"; // Add an "|" character to the variable 'line'; // Add an "|" character to the variable 'line'.
  counter++; // The value of 'counter' is incremented (but as it is a string, the increment does not work as expected)
  console.log(line); // The current value of 'line' is printed to the console.
}
				
			

However, there is an important detail in this code. The variable counter is initialized with the string value "1" instead of a number. This means that when the comparison is performed in the loop whileIf you do not use a string comparison, the comparison will be based on string comparisons instead of numbers. This may generate unexpected results.

The loop while should work correctly if you initialize counter as a number:

				
					let counter = 1; // Initialize the variable 'counter' with the numeric value 1
let line = ""; // Initialize the variable 'line' as an empty string
console.log("@"); // The "@" character is printed to the console.

while (counter <= 10) {
  line += "|"; // Add an "|" character to the variable 'line'; // Add an "|" character to the variable 'line'.
  counter++; // Increment the value of 'counter'.
  console.log(line); // Print current value of 'line' to console
}
				
			

With this correction, the while will execute the code block inside it repeatedly until it counter is greater than 10. At each iteration, a character "|" is added to the variable line and the current value of line. As a result, you will see a series of lines with an increasing number of vertical bars "|" on each line.

Using a loop to display comments hosted in an array

				
					let comments = 10;
for (i = 1; i <= comments; i += 2) {
  console.log("Comment: " + i);
}
				
			

The code uses a loop for to print a series of numbered comments. Here is a step-by-step explanation:

				
					let comments = 10; // The 'comments' variable is initialized with the value 10.

for (i = 1; i <= comments; i += 2) {
  // The 'for' loop starts with i = 1, runs as long as i is less than or equal to 'comments',
  // and after each iteration i is incremented by 2

  console.log("Comment: " + i);
  // The message "Comment: " followed by the current value of i is printed to the console.
}
				
			

The loop for in this code is executed with the following values of i: 1, 3, 5, 7 y 9. This is because i starts at 1 and increases by 2 at each iteration.

How to use loops to create a customer receipt program

The code performs certain operations to populate an HTML table with information related to customers, their receipts and item prices. Let's break down the code step by step:

				
					const customers = ["John S.", "Emma M.", "Frank T."];
const receipts = [
  ["eggs", "white bread", "milk"],
  ["milk", "cheese", "butter", "pancake mix", "flour"],
  ["cereal", "whole wheat bread", "milk", "cheese", "eggs", "vanilla"]
];
const prices = {
  // ... (definition of prices for various items)
};

function setElementText(id, text) {
  document.getElementById(id).innerText = text;
}

function populateTable() {
  // Your code starts here
  for (let i = 0; i < customers.length; i++) {
    const customer = customers[i];
    const receipt = receipts[i];
    let receipt_list = "";
    let sum = 0;

    for (let j = 0; j < receipt.length; j++) {
      const item = receipt[j];
      const price = prices[item];
      receipt_list = receipt_list + item + "\n";
      sum = sum + price;
    }

    setElementText("customer" + i.toString(), customer);
    setElementText("receipt" + i.toString(), receipt_list);
    setElementText("total" + i.toString(), sum);
  }
}
				
			

Here is a summary of what the code does:

  1. Three matrices are defined:

    • customersContains the names of the customers.
    • receiptsContains the lists of products purchased by each customer.
    • prices: An object that stores the prices of the items.
  2. The function setElementText(id, text) is used to change the content of an HTML element by its ID.

  3. The function populateTable() populates an HTML table with customer information, receipts and totals:

    • The first loop for each customer in customers.
    • The list of products purchased by the current customer is obtained (receipt).
    • Variables are initialized receipt_list to store the names of the products and sum to store the total amount of the purchase.
    • The second loop for scrolls through each item on the customer's receipt.
    • The price of the current item is searched for in the object prices.
    • The list of products purchased is updated and the price is added to the total.
    • Finally, the function setElementText to update the corresponding HTML elements with the customer's data, receipt and total.

In short, the code takes customer data, their receipts and item prices to populate an HTML table with this information.

				
					const customers = ["John S.", "Emma M.", "Frank T."];
const receipts = [
  ["eggs", "white bread", "milk"],
  ["milk", "cheese", "butter", "pancake mix", "flour"],
  ["cereal", "whole wheat bread", "milk", "cheese", "eggs", "vanilla"]
];
const prices = {
  "eggs": 3.50,
  "white bread": 4.50,
  "milk": 5.99,
  "cheese": 6.50,
  "butter": 3.45,
  "pancake mix": 4.50,
  "flour": 5.75,
  "cereal": 4.50,
  "whole wheat bread": 6.50,
  "vanilla": 8.75
};

function setElementText(id, text) {
  document.getElementById(id).innerText = text;
}

function populateTable() {
  // Your code starts here
  for (let i = 0; i < customers.length; i++) {
    const customer = customers[i];
    const receipt = receipts[i];
    let receipt_list = "";
    let sum = 0;
    for (let j = 0; j < receipt.length; j++) {
      const item = receipt[j];
      const price = prices[item];
      receipt_list = receipt_list + item + "\n";
      sum = sum + price;
    }
    setElementText("customer" + i.toString(), customer);
    setElementText("receipt" + i.toString(), receipt_list);
    setElementText("total" + i.toString(), sum);
  }
}
				
			
				
					<!doctype html>
<html>
  <head>
    <title>Receipt Summary</title>
    <script type="text/javascript" src="index.js"></script>
    <link rel="stylesheet" href="style.css">
  </head>
  <body onload="populateTable()">
    <div id="project">
      <h2>Customer Receipts</h2>
      <table>
        <tr>
          <th class="bold">Customer:</th>
          <th id="customer0"></th>
          <th id="customer1"></th>
          <th id="customer2"></th>
        </tr>
        <tr>
          <td class="bold">Items:</td>
          <td id="receipt0"></td>
          <td id="receipt1"></td>
          <td id="receipt2"></td>
        </tr>
        <tr>
          <td class="bold">Total:</td>
          <td id="total0"></td>
          <td id="total1"></td>
          <td id="total2"></td>
        </tr>
      </table>
    </div>
  </body>
</html>
				
			
				
					body {
  background-color: #273C75;
  color: white;
}

#project {
  font-family: sans-serif;
}

.bold {
  font-weight: bold;
}

h3 {
  margin-top: 20%;
}

table {
  border-collapse: collapse;
  font-size: 10px;
}

tr,
th,
td {
  border: 5px solid white;
  padding: 10px;
}
				
			
If you liked the article, help me share it!
Picture of Muari Azpeitia
Muari Azpeitia