Using a function’s arguments array in JavaScript

By David Pratt / Tags: , / No Comments / Published: 29-11-09

When you pass parameters into a function, there is an easy way to retrieve them without first pre-defining them. There is something called the arguments array array which allows you to access the information passed into a function. Now, because you can determine the size of the arguments array it allows you to do useful things like:

function sum() {
  var total = 0;
  for (var i=0; i < arguments.length; i++) {
    total = total + arguments[i];
  return total;
sum(5,4,3); //returns 12

What this function does is take any number of parameters and then add them together.

You can also do the arguments.length technique in reverse by using the length method against the function. This will then give you the number of variables that are expected by a function. For example:

function sum(x, y, z){
    return x + y + z;
console.log(sum.length); // returns 3, as that is the number of expected parameters.

I can't say I use either of these techniques a great deal, but they are useful to know nonetheless!

Category: Tech

Tags: ,

Posted: on November 29th, 2009 at 1:35 pm.

Feeds: RSS 2.0

Leave a reply