Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Functions : Argument Lists Object

Monday, July 16, 2018

JavaScript Functions : Argument Lists Object

In JavaScript when you define a function you get a built-in Arguments object, this object is an array-like object that puts the arguments/parameters of the your function in an object which can be accessed via indexes much like an array.

This can be useful if you have a function that takes multiple parameters, but you don't know how parameters there will be.  Let's modify our addNumbers function so that it can add more than two numbers using the Arguments object.

        function addNumbers() {
            var sum = 0;

            for (var i = 0; i < arguments.length; i++)
                sum += arguments[i];

            return sum;

        console.log("The sum of the numbers are " + addNumbers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

If you remember our previous addNumbers function it only takes two numbers and and add them.

With no parameters specified we can specify as many parameters as we want and add the numbers based on the number of parameters to get the total.  The draw back with this approach is that we don't have any named parameters, which means that we can only to the parameters via the arguments object like this argument[i].  However, we don't have to know the exact number of parameters ahead of time for our function.  So there is a trade-off.

No comments:

Post a Comment

Search This Blog