This page looks best with JavaScript enabled

Optional arguments using spread while calling functions

 ·   ·  ☕ 1 min read

How about using the spread operator for handling optional arguments, or for null arguments?

Consider this code -

1
2
3
function sum(x, y, z) {
  return x + y + z;
}

We can choose to pass ‘z’ or not, but ignoring ‘y’ returns an error.

1
2
3
4
5
6
7
8
9
console.log(sum(1, 2, 3));
// 6

console.log(sum(1, 2));
// NaN

console.log(sum(1, , 3));
// error: Unexpected token ,

Sure, you can use a null or undefined in the middle and get away with it. But, you could also replace that with the spread operator like so -

1
2
3
4
5
6
7
8
console.log(sum(...[1, 2, 3]));
// 6

console.log(sum(...[1, 2]));
// NaN

console.log(sum(...[1, , 3]));
// NaN

You still get a NaN, but no run time errors!

We use spread operator to destructure the array with zero or more elements, and pass it to the said function. While it is minimal overhead work at the caller end, the signature of the called function will remain intact.

Although the use of spread operator like the above is interesting, consider using named arguments within a single object in your functions. Also, see rest parameters.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things