With this post I’ll discuss what is arguments in JavaScript? Focus on its structure and point out key differences between an array and arguments.

What is ‘arguments’? It is an array-like object which contains all the parameters passed to a function.

In JavaScript there are several ways to call a function, of which, the simplest is to directly call a function with some parameters, based on the functionality of the function.

function add(a, b){
 return a+b;
}

var result = add(3,2);
console.log(result);

Although, the function above expects two parameters, more can be sent to the function add. So, what would happen if following change is made to the function call?

var result = add(3,2,4);

The code would still execute, and result would remain same. What happened to the third parameter? It would still be accessible via the function add. Modify the code as following –

function add (a, b){
 console.log(arguments);
 return a + b;
}

The second statement would log [2, 3, 4]. The arguments array-like object would hold all the parameters passed to the function add.

Although arguments logs data as an array, yet I’m using array-like to refer to it. This is because, arguments is an array-like object. It’s similar to an array, as it contains indexed elements and has length property. However, arguments doesn’t provide any of the array methods, such as sort(), splice(), slice(), and others.

While working on a task, it would help to convert arguments to array, as it would enable using array methods on arguments. How to convert arguments to an array?

function argToArr(){
 var arg = [].slice.call(arguments);
 return arg;
}
var arr = argToArr(1,2,3,4,5);
arr.push(6);
console.log(arr)

The above snippet should log [1, 2, 3, 4, 5, 6]. And, arr can be manipulated as an array.

I hope this post helps you get a better understanding about JavaScript arguments. Feel free to share your view in the comment sections.