-1

While creating this short script I came across this error Uncaught TypeError: Cannot read properties of undefined (reading 'brand'). Below is the code that I wrote. Its says error is on the line <p class="brand">${bikes[i].brand}</p>

const bikes = [
  {
    brand: "Specialized",
    name: `Specialized STUMPJUMPER EVO - 29" Carbon Mountainbike - cast battleship`,
    price: "5.461,34 €",
    image: "../img/mtb/Stumpjumper.jpg",
  },
];

for (let i = 0; i <= bikes.length; i++) {
  let bikeElement = `
<div class="card">
  <p class="brand">${bikes[i].brand}</p>
</div>`;
  createBikes();
  function createBikes() {
    document
      .getElementById("container")
      .insertAdjacentHTML("beforeend", bikeElement);
  }
}
Bulat
  • 3
  • 1

1 Answers1

2

You need to switch your for loop to use < instead of <=. The length of your array is 1. If i == 1, it will be unable to find the array[1] item, since arrays are indexed starting with 0.

const bikes = [
  {
    brand: "Specialized",
    name: `Specialized STUMPJUMPER EVO - 29" Carbon Mountainbike - cast battleship`,
    price: "5.461,34 €",
    image: "../img/mtb/Stumpjumper.jpg",
  },
];

for (let i = 0; i < bikes.length; i++) {
  let bikeElement = `
<div class="card">
  <p class="brand">${bikes[i].brand}</p>
</div>`;
  createBikes();
  function createBikes() {
    document
      .getElementById("container")
      .insertAdjacentHTML("beforeend", bikeElement);
  }
}
<div id="container"></div>
Richard Henage
  • 1,758
  • 1
  • 3
  • 10