Javascript - Function arguments object

Introduction

An ECMAScript function doesn't care arguments count and their types.

A function defined to accept two arguments doesn't mean you can pass in only two arguments.

You could pass in one or three or none.

Arguments in ECMAScript are represented as an array.

The array is always passed to the function, but the function doesn't care what is in the array.

You can use the arguments object inside a function to retrieve the values of each argument that was passed in.

The arguments object acts like an array though it isn't an instance of Array.

You can access each argument using bracket notation.

The first argument is arguments[0], the second is arguments[1], and so on.

You can determine arguments' count by using the length property.

You can access the parameters as follows:

function displayMessage() {
    console.log("Hello " + arguments[0] + ", " + arguments[1]);
}

In the code above, there are no named arguments.

The arguments object can be used to check the number of arguments via the length property.

The following example outputs the number of arguments passed into the function each time it is called:

function countArguments() { 
    console.log(arguments.length); 
} 

countArguments("string", 45);    //2 
countArguments();                //0 
countArguments(12);              //1 

This example shows alerts displaying 2, 0, and 1.

Related Topics