Javascript Function Arguments

Learning Objectives

  1. How javascript arguments work internally
  2. How to determine the total number of arguments passed
  3. How to determine the currently executing function
  4. How to make a function to accept optional parameters
  5. How to make a function to accept infinite arguments

How Javascript Aruguments Work?

Arguments in javascript are received as an Array. This statement can be better understood using an example:

function test( a, b ) {
    alert( 'a: ' + a + '\n' + 'b: ' + b );
}
 
window.onload = function() {
    test( 'arg1', 'arg2' );
}

Test is a simple function receiving two arguments a and b whose values are displayed using alert(). As I wrote above that arguments are passed as an Array so we can also access both a and b in test() function like this:

alert( arguments[0] ); //argument a
alert( arguments[1] ); //argument b

Total Arguments and Running Function

We can also very easily find the total number of arguments passed using the length property and currently executing function using callee property of arguments Array.

alert( arguments.length ); //2 in our case
alert( arguments.callee ); //displays code of currently running function which is test()

Optional Parameters

As we know that arguments in javascript are passed as an Array. It means that every parameter is optional in javascript functions. It’s not necessary to pass parameters specified in the function argument list. Let’s take a look at an example.

function test( a, b ) {
        alert( 'a: ' + a + '\n' + 'b: ' + b );
    }
 
    window.onload = function() {
        test(); //interpreter wont give you an error here
}

In the above code, javascript interpreter won’t give you an error when calling test() function without parameters. You maybe wondering what will be the values of argument a and argument b? If any argument is not passed, its value is undefined. So in the above code, a: undefined and b: undefined will be displayed.

Infinite Arguments

Another thing which is proved from above example is that it will also not give any error when passing more arguments than specified in the argument list.

test( 'arg 1', 'arg 2', 'arg 3', 'arg 4' );

This is very interesting point to remember. You can pass any number of arguments to a function. Missing arguments contain undefined and extra arguments can be accessed using “arguments” Array. Following example display list of all arguments passed to a function using loop.

function test() {
    for( var i = 0; i < arguments.length; i++ ) {
        document.writeln( 'Argument-' + i + ': ' + arguments[ i ] + '<br />' );
    }
}
 
window.onload = function() {
    test( 'arg 1', 'arg 2', 'arg 3', 'arg 4' );
}

Reference

  1. Array arguments on MDC

comments powered by Disqus