0

I found a javascript code that has:

for each (var A in B){   // B is an array [] and has been pushed with some elements
     // logic to deal with A in for loop
}

And I open this project in VScode, but it shows me there are syntax error in line:

for each (var A in B){

But I tried to run it and print traces, I found it worked well(it successfully loops every element in B). So is this syntax correct? If not, what is the recommended way to loop through an array in this case? Thanks!

coder2
  • 37
  • 5
  • `for (let i of [1,2,3]) { console.log(i) };`, see [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) – Pac0 Sep 02 '20 at 04:38
  • Also, prefer `of` over `in`, and `let` or `const` over `var` ([see this](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var)). And no need of `each`. – Pac0 Sep 02 '20 at 04:39
  • This Question has been answered in pas as well you can get Help from this post. https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript – WaqarAli Sep 02 '20 at 05:32

1 Answers1

0

the syntax error is valid cause the forEach() in javaScript is a method for array objects and it takes a callback function which it apply on each element of the array, and we can access the methods by using dot notation. So the correct syntax for using forEach loop in your case will be as follows:-

B.forEach(A => { 

//logic to deal with A
});

you can refer to this article if you want more clarity https://www.freecodecamp.org/news/javascript-foreach-how-to-loop-through-an-array-in-js/