while loops (for when the number we are iterating over is unknown)

PHOTO EMBED

Mon May 27 2024 08:13:39 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #while #loop

// use while loops when the number of items we are looping over are unknown


let items = [
  { id: 1, name: "Item 1", price: 10.99 },
  { id: 2, name: "Item 2", price: 15.49 },
  { id: 3, name: "Item 3", price: 7.99 },
  { id: 4, name: "Item 4", price: 12.0 },
  { id: 5, name: "Item 5", price: 9.5 },
];

let i = 0; // counter variable

let numberOfItems = items.length ?? 0; // if the number of items is not a number give me 0;
console.log(numberOfItems);

while (i < items.length) {
  let { id, name, price } = items[i]; // Destructuring assignment
  console.log(`ID: ${id}, Name: ${name}, Price: $${price}`);
  i++;
}
content_copyCOPY