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

Friday, December 24, 2021

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.


  1. really very useful information given by you. this post is very informative. the article is nicely explained and easy to understand. thanks for sharing this post with us.


  2. This article having so much of amazing information. Today I learned so many things in this blog post.
    Keep doing your awesome work>


Search This Blog