DEV Community

FabrizioOnorio
FabrizioOnorio

Posted on

How to write a function that only accepts an exact number of arguments

How to write a function that only accepts an exact number of arguments

If you find yourself having to write a function that can only accept a predefined number of arguments there are several ways to approach this using vanilla JavaScript , hereI’ll describe 2 simple ways of doing this, using the arguments object and rest parameters (this last one is preferred for ES6 and arrow functions).

The arguments object:

arguments is an array object accessible inside functions that contains the values of the arguments passed to that function as explained on https://developer.mozilla.org/.

Let's see this on use:

function add(a, b, c) {

      return arguments[0] + arguments[1] + arguments[2];

    };
Enter fullscreen mode Exit fullscreen mode

This is the same thing as doing:

function add(a, b, c) {

      return a + b + c;

    };
Enter fullscreen mode Exit fullscreen mode

In this case, if we want to accept only 3 arguments, no more, no less we could do:

function add(a, b, c) {

      if (arguments.length === 3) {

        return a + b + c;

      }

    };
Enter fullscreen mode Exit fullscreen mode

Rest parameters:

The rest parameter allows a function to accept an indefinite number, or in our case defined number of arguments as an array in JavaScript.

Let’s achieve the same as before but with the rest parameters this time:

function add(...args) {

      if (args.length === 3) {

        return args[0] + args[1] + args[2];

      }

    };
Enter fullscreen mode Exit fullscreen mode

In this case args represents the array we access our values from. In order to be accessed it is essential to use the ‘…’. Furthermore, this should be the way to go in arrow functions as previously explained.

I hope this was useful.

Happy coding 🚀

Top comments (0)