Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript: Function Arguments

In JavaScript, a function can be called using any number of arguments. Suppose if a function is defined with 4 arguments, it is not necessary to pass all the 4 arguments while calling the function.

For example,
function processData(a, b, c, d){

}

Above function can be processed like below.
processData(10);
processData(10, 20);
processData(10, 20, 30);
processData(10, 20, 30, 40);
processData(10, 20, 30, 40, 50); //50 is unnamed argument
processData(10, 20, 30, 40, 50, 60); // 50 and 60 are unnamed arguments

function.html





function arguments



"text/javascript">
function processData(a, b, c, d) {
document.write("a = " + a + " b = " + b + " c = " + c + " d = " + d + "

"
);
}

processData(10);
processData(10, 20);
processData(10, 20, 30);
processData(10, 20, 30, 40);
processData(10, 20, 30, 40, 50);





Open above page in browser, you can able to see following data.
a = 10 b = undefined c = undefined d = undefined

a = 10 b = 20 c = undefined d = undefined

a = 10 b = 20 c = 30 d = undefined

a = 10 b = 20 c = 30 d = 40

a = 10 b = 20 c = 30 d = 40

Accessing unnamed arguments of a function
By using arguments keyword, you can access all the arguments passed to the function.

function processData(a){
         for(var i=0; i
                  document.write(arguments[i] + " ");
         }
         document.write("

");
}
                          
functionArgs.html






Function Arguments



"text/javascript">
function processData(a) {
document.write("Arguments are : ");
for (var i = 0; i arguments.length; i++) {
document.write(arguments[i] + " ");
}
document.write("

"
);
}

processData();
processData(10);
processData(10, 20);
processData(10, 20, 30);





Open above page in a browser, you can able to see following data.

Arguments are :

Arguments are : 10

Arguments are : 10 20

Arguments are : 10 20 30


Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

JavaScript: Function Arguments

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×