DEV Community

loading...

Discussion on: 5 ways to refactor if/else statements in JS functions

Collapse
yerlanyr profile image
yerlanyr

This thing I use a lot!

function foo(arg) {
  if (arg === "a") return 1
  if (arg === "b") return 2
  return 3 //default value
}
Enter fullscreen mode Exit fullscreen mode

At this point I always format if statements as if code block, because condition in if statement could be very long so that return would be lost dangling somewhere outside of field of view which could lead to bad mistakes.

function foo(arg) {
  if (arg % 3 === 0 && arg % 5 == 0 /* let's pretend there is very long condition*/) return 'foobar'
  if (arg % 3 === 0) return 'foo'
  if (arg % 5 === 0) return 'foo'
}
Enter fullscreen mode Exit fullscreen mode

Data structures are good for reducing code's complexity. Sometimes it is clearer to use switch case or if's.

Collapse
sylwiavargas profile image
Sylwia Vargas Author

I love these examples — thank you!

condition in if statement could be very long so that return would be lost dangling somewhere outside of field of view
I really couldn't agree more. This is definitely one of the main things that bother me about JS specifically — that there's no strict standard/expectation of writing really short code.