DEV Community

Discussion on: Code Smell 53 - Explicit Iteration

Collapse
 
shadowtime2000 profile image
shadowtime2000

The Right JS code is kind of wrong syntax wise and stuff. This would be the correct code:


for (color in colors) {
  print(colors[color]);
}

//Closures and arrow functions
colors.foreach(color => console.log(color);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt
  • Depends on the programming language; but JavaScript in is damn confusing.
  • A closing bracket is missing at the end.
Collapse
 
qm3ster profile image
Mihail Malo • Edited
  1. Yeah, unless they wanted to print keys (including inherited), they should have used of not in.
  2. a closing parenthesis*
Thread Thread
 
mcsee profile image
Maxi Contieri

corrected! thank you!

Collapse
 
bugrahasbek profile image
Buğra Hasbek

I don't use js and this confused the hell out of me at first sight :) i was expecting color to be an element in colors but it is used as an index? I think I prefer the c++ way

for (auto color:colors) 
  print(color);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mouseeatscat profile image
Michel Descoteaux • Edited

Or in this case it could have been simplified even further to:

for (color of colors) {
  console.log(color);
}

//Closures and arrow functions
colors.forEach(color => console.log(color));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ifarmgolems profile image
Patrik Jajcay
colors.forEach(console.log);
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
mcsee profile image
Maxi Contieri

Nice!