DEV Community

Discussion on: Fundamentals of Functional JavaScript

Collapse
marwaneb profile image
Marwan El Boussarghini • Edited on

Very cool article thanks for writing it. I'm also super enthusiastic about FP and it's good that people write content about it πŸ˜„

About the section "a. Early Returns" I tend to disagree with you: let's take this code

function getPokemonWeaknesses({ types = [] }) {
  let weaknesses = []

  if (types.includes('WATER')) {
    if (!types.includes('EARTH')) {
      weaknesses = ['ELECTRICITY']
    } else {
      weaknesses = ['PLANT']
    }
  }
  if (types.includes('FIRE')) {
    if (!types.includes('WATER')) {
      weaknesses = ['WATER']
    } else {
      weaknesses = ['PSY']
    }
  }
  return weaknesses
}
Enter fullscreen mode Exit fullscreen mode

I generally feel that I would have far more troubles debugging it and understanding it at first glance than a code like this one:

function getPokemonWeaknesses({ types = [] }) {
  if (types.includes('WATER')) {
    if (!types.includes('EARTH')) return ['ELECTRICITY']
    return ['PLANT']
  }

  if (types.includes('FIRE')) {
    if (types.includes('WATER')) return ['PSY']
    if (types.includes('PLANT')) return ['COMBAT']
    return ['PLANT']
  }

  return []
}
Enter fullscreen mode Exit fullscreen mode

Maybe it's more of a personal preference but I would be super interested to read how people feel about this πŸ‘πŸ½

PS: sorry for my knowledge on Pokemon types, it has been a long time since I've played any Pokemon game πŸ˜…

Collapse
anmshpndy profile image
Animesh Pandey Author • Edited on

Haha, thanks. 😊

In the end, I guess the point is to make the code more readable. In your example, for sure, the early returns can look more obvious to read. In many cases, they make people lose the flow and intention of the code.

My own preference would certainly depend upon the specific case under consideration, but this was a piece of general advice I have received from many throughout my journey.

Anyway, the main idea of mentioning early returns in the article was to explain that they exist and can be used as an exit from a function (as a function output), but if they complicate the readability too much, it's better to have a single return.

Even my PokΓ©mon knowledge is rusty now. Looking forward to the Diamond and Pearl remakes, and PokΓ©mon Legends. :D

Hope you'll stick around for more! Take care!

Collapse
marwaneb profile image
Marwan El Boussarghini

Thanks for the answer, I agree we always need to be cautious about readability !
I always like to challenge my knowledge and the things I do without even thinking about them, it's cool to read some interesting articles that help me do so πŸ‘πŸ½