This page looks best with JavaScript enabled

Process one or multiple arguments within a function

 ·   ·  ☕ 2 min read

Let’s say you have to write a function that doubles a given number. You also find out that you may get one number (in which case double that number), or multiple numbers (double all numbers).

The first thought that comes to mind is to -

  • use different functions (or)
  • check type of input and process differently

Consider the below code -

1
2
3
4
5
6
7
8
9
const double = x => {
  if (typeof x == "object") return x.map(val => val * 2);
  else return x * 2;
};

console.log(double(2));
// 4
console.log(double([2, 3]));
// [ 4, 6 ]

The given option is workable, but there is a shortcut way to do the same.

1
2
3
4
5
6
7
8
9
const double = x => {
  const input = [].concat(x);
  return input.map(val => val * 2);
};

console.log(double(2));
// [ 4 ]
console.log(double([2, 3]));
// [ 4, 6 ]

The added advantage is the consistent output signature - the function output is always an array.

So, why would you want to do this?

  1. Use same function without changes for one or more than one arguments
  2. Lower the number of function calls - it’s a better option as compared to calling function in a loop or having branched out logic for different types

Of course, you cannot have this kind of logic in all places. But, have this option in the back of your mind while designing your functions.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things