DEV Community

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

Collapse
 
vidhill profile image
David Hill

One thing I see on occasion,

is the resulting action being calling a function, with the only difference being some logic determining what a certain argument should be

const doSomething = function (arg1, arg2) {
  if (arg1 === "condition") {
    return callA(arg1, arg2, 10);
  }
  return callA(arg1, arg2, 0);
};
Enter fullscreen mode Exit fullscreen mode

versus

const doSomethingB = function (arg1, arg2) {
  const arg3 = arg1 === "condition" ? 10 : 0;
  return callA(arg1, arg2, arg3);
};
Enter fullscreen mode Exit fullscreen mode

Another one is calling functions with the same arguments, with the only difference being which function to call:

const doSomething = function (arg1, arg2, arg3) {
  if (arg1 === "condition") {
    return callA(arg1, arg2, arg3);
  }
  return callB(arg1, arg2, arg3);
};
Enter fullscreen mode Exit fullscreen mode

Versus

const doSomething = function (arg1, arg2, arg3) {
  const fnToCall = arg1 === "condition" ? callA : callB;
  return fnToCall(arg1, arg2, arg3);
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sylwiavargas profile image
Sylwia Vargas

Thank you for these examples! Coming from Ruby, this is something I definitely instinctively lean towards and catch myself writing sometimes 😂 I'll include you're examples in the blog post!