DEV Community

Discussion on: Avoid use IF on our JS scripts

Collapse
 
macarie profile image
Raul • Edited

The article is nice, it gives some cool alternatives that not everyone might know about, a handful of which we use at work.

As others said, tho, some are harder to read.

A little side note about #4 and #5: it would be better to re-use the object and not to create it every time a function is called (eg: creating it inside array.map(), etc), it slows down your code a lot!

I'm saying this because it might not be obvious and also because I've had to refactor some code that was doing the exact same thing after I got hired ๐Ÿ˜Š

A better approach would be to do something like this instead:

const createDogSwitcher = () =>{
  const objectSwitch = {
    border: 'Border Collies are good boys and girls.',
    pitbull: 'Pit Bulls are good boys and girls.',
    german: 'German Shepherds are good boys and girls.',  
  }

  const defaultString = 'Im the default.'

  return (breed) => objectSwitch[breed] || defaultString
}

const dogSwitch = createDogSwitcher()

dogSwitch('border xxx')

// Now use `dogSwitch` inside `map()`
Enter fullscreen mode Exit fullscreen mode

If you want even better performance out of this, you can use a Map() instead of an object ๐Ÿ––๐Ÿผ

Edit: I think you have two #5s ๐Ÿค”

Collapse
 
damxipo profile image
Damian Cipolat

thanks for comments! the idea was make an arrow function that return an object. I had thought about this option too, it is more semantic but much more code. It is in each developer as you feel more comfortable.