Saturday 1 September 2018

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
<!DOCTYPE html>

<html>

<head>
    <title>function arguments</title>
</head>

<body>
    <script type="text/javascript">
        function processData(a, b, c, d) {
            document.write("a = " + a + " b = " + b + " c = " + c + " d = " + d + "<br /><br />");
        }

        processData(10);
        processData(10, 20);
        processData(10, 20, 30);
        processData(10, 20, 30, 40);
        processData(10, 20, 30, 40, 50);
    </script>
</body>

</html>

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<arguments.length; i++) {
                  document.write(arguments[i] + " ");
         }
         document.write("<br /><br />");
}
                          
functionArgs.html

<!DOCTYPE html>

<html>

<head>
    <title>Function Arguments</title>
</head>

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

        processData();
        processData(10);
        processData(10, 20);
        processData(10, 20, 30);
    </script>
</body>

</html>

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

No comments:

Post a Comment