Accesing variables inside the forEach loop

i have little problem in accessing variables from a forEach loop, that loops around an array of objects, outside the loop. i already tried declaring variables and assigning them to the ones in the forEach loop but it was unsucsessful because it only returns the first value.

let bestPrice;
let injectInstruments;
allInstruments.forEach(function (instrument) {
    
    let price = instrument.price;
    let type = instrument.type;
    let description = instrument.description;
    let picture = instrument.picture;
   
     injectInstruments =instrumentsContainer.innerHTML= `<div  hidden 
    instrumentType='${type}'class="box instrument" price="${price}">
        <img class="instrument-image" src="${picture}" alt="">
       <h6 class="price">${price}</h6>
        <p class="instrument-description">${description}</p>
    </div>`
   bestPrice=price
})
console.log(injectInstruments);
console.log(bestPrice);

Answer

Issue

  • bestPrice is overwritten every loop.
  • instrumentsContainer.innerHTML is overwritten every loop.
  • You don’t need to access injectInstruments to insert html because .innerHTML = '' changes html.
  • injectInstruments =instrumentsContainer.innerHTML='<div ...>' has 3 equals =, which causes a syntax error.

Solution

  • Use .insertAdjacentHTML() instead of .innerHTML. The former adds html into a container, the latter overwrites a container’s content completely.
  • If you want to access only prices, store prices in an array.

// Get the container <div>
const instrumentsContainer = document.querySelector('div');

const allInstruments = [{
    price: 100,
    type: 'something',
    description: 'lorem ipsum',
    picture: './image1.jpg'
  },
  {
    price: 200,
    type: 'something2',
    description: 'lorem ipsum2',
    picture: './image2.jpg'
  },
];

// An array to store prices
let bestPrices = [];
  
function myFunction() {
  allInstruments.forEach(function(instrument) {

    let price = instrument.price;
    let type = instrument.type;
    let description = instrument.description;
    let picture = instrument.picture;

    // HTML
    let html = `<div instrumentType='${type}'class="box instrument" price="${price}">
        <img class="instrument-image" src="${picture}" alt="${picture}">
       <h6 class="price">${price}</h6>
        <p class="instrument-description">${description}</p>
    </div>`;

    // Insert the html to the end of the <div>
    instrumentsContainer.insertAdjacentHTML('beforeend', html);

    // Store a price to the array
    bestPrices.push(price);
  });
}

// Execute myFunction();
myFunction();

// Check bestPrices
console.log(bestPrices);
<div></div>

Personally, I don’t think it’s necessary to store prices in an array. If you want to get the lowest price, you can do like this:

const allInstruments = [{
    price: 100,
    type: 'something',
    description: 'lorem ipsum',
    picture: './image1.jpg'
  },
  {
    price: 200,
    type: 'something2',
    description: 'lorem ipsum2',
    picture: './image2.jpg'
  },
];

let bestPrice = Math.min(...allInstruments.map(e => e.price));

console.log(bestPrice)

Leave a Reply

Your email address will not be published. Required fields are marked *