DEV Community

Discussion on: Code Smell 53 - Explicit Iteration

Collapse
 
qm3ster profile image
Mihail Malo
  1. You want to use of with iterators, in is for string keys of objects (including inherited).
  2. for in and for of syntax in js looks like for (const ident of expression) (where const could be let or var and of could be in)
  3. there's a missing ) in the last statement
  4. most commonly available print fn in js is console.log
  5. Array method is called forEach (capitalization)

so, all in all:

const colors = ['red', 'green']
const {log} = console

for (const color of colors)
  log(color)

// closure/arrow function
colors.forEach(color => log(color))
Enter fullscreen mode Exit fullscreen mode

if for some reason you have to use in to iterate over values of an object, it's typically done like this (to avoid iterating over inherited keys)

for (const key in obj)
  if (obj.hasOwnProperty(key))
    do_thing(key, dict[key])
Enter fullscreen mode Exit fullscreen mode

however you should prefer the new iterators, such as Object.keys(), Object.values() and Object.entries().
As such, the above becomes:

for (const [key, val] of Object.entries(obj))
    do_thing(key, val)
Enter fullscreen mode Exit fullscreen mode

Finally, if you see yourself operating on keys of an Object generically like this, you might instead be looking for Map, which naturally iterates by "entries", and supports non-string keys.

const ref = {two: 2}
const m = new Map([[1, "val1"], [ref, "val2"]])
for (const [k,v] of m)
  console.log("key", k, "value", v)
Enter fullscreen mode Exit fullscreen mode

See also Set, WeakMap, WeakSet

Collapse
 
mcsee profile image
Maxi Contieri

Wow!

How many detaill!

I will make your corrections

Nevertheless i use many different languages on all my code smells and i like to think them as pseudo code without entering any language details. Your solution is clearly a better one but it is too tied to a particular language.

Collapse
 
qm3ster profile image
Mihail Malo

What other languages do you use?

Thread Thread
 
mcsee profile image
Maxi Contieri

see my code smells

up to now:
javascript
pyhton
php
golang
java
ruby

Language is accidental
Code smells are not related to any particular language

I write code snippets as examples but I think them most as pseudocode