JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to write JavaScript function that accepts variable number of arguments?

Before you learn how to create a function with variable arguments, you need to understand what are arguments and parameters in JavaScript. Arguments are the values that are passed to the function during a function invocation, whereas parameters are the variables that are declared in function declaration or definition.

function show(a, b){
  console.log(a);
  console.log(b);
}
show(2, 3);

In this example, variables a and b are parameters. 2 and 3 are arguments.

What is a variable number of arguments?

Variable number of arguments means the function can accept any number of arguments. In JavaScript, there are two ways of writing a function that accepts any number of arguments:

  • Using the arguments object.
  • Using the rest parameter.

How to use the arguments object to create a function that accepts any number of arguments?

Every function in JavaScript has the arguments object that stores all the arguments passed to the function.

Using square brackets notation, you can access the arguments. The first argument is at the 0th position, the second argument is at the 1st position, and so on.

Let's see how to use the arguments object with the help of an example:

function display(){
  console.log(arguments);
  console.log("First argument is " + arguments[0]);
  console.log("Second argument is " + arguments[1]);
  console.log("Third argument is " + arguments[2]);
}
 
display('ReactJS', 'AngularJS', 'VueJS');

Output

{
  0: "ReactJS",
  1: "AngularJS",
  2: "VueJS"
}
First argument is ReactJS
Second argument is AngularJS
Third argument is VueJS

To learn more about the arguments object, visit How to use arguments object in JavaScript Function?

How to use the rest parameter to create a function that accepts any number of arguments?

The rest parameter was introduced in the ES6 standard. It converts the arguments to an array. You can use for/of, forEach(), and other loops to iterate through the arguments.

function display(...args){
  console.log(args);
  for(let a of args){
    console.log(a);
  }
}
 
display('ReactJS', 'AngularJS', 'VueJS');

Output

["ReactJS", "AngularJS", "VueJS"]
ReactJS
AngularJS
VueJS

A function can have at most one rest parameter. The rest parameter must be the last parameter of the function.

function display(arg1, arg2, ...args){
   console.log(arg1);
   console.log(arg2);
   console.log(args);
}
display(1, 2, 3, 4, 5, 6);

Output

1
2
[3, 4, 5, 6]

To learn more about the rest parameter, visit How to use the rest parameter in JavaScript?

Recommended Posts