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
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

3

Try this one

(offer.products || []).forEach(function(product) {
   console.log(product);
});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
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,930
  • 2
  • 36
  • 51