0

I have a json array that I want to iterate as follows:

offer.products.forEach(function(product) {
   console.log(product);
});

Problem: if products list is null or empty or undefined, this will produce an error.

Question: how is safe iterations done properly in javascript?

membersound
  • 74,158
  • 163
  • 522
  • 986

2 Answers2

3

Try this one

(offer.products || []).forEach(function(product) {
   console.log(product);
});
Jaromanda X
  • 1
  • 4
  • 64
  • 78
1

Just add the fitting checks:

if (offer.products) { //blocks products==null and products==undefined
    offer.products.forEach(function(product) {
        console.log(product);
    });
}

Empty should not be a problem, since forEach should not do anything if products is empty.

Dakkaron
  • 5,468
  • 2
  • 35
  • 49