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.

    <script>
        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));
    </script>









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.




4 comments:

  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.
    https://www.milanosrenfrew.uk/

    ReplyDelete

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

    ReplyDelete
  3. Casinos & casinos | Microgaming | Microgaming
    Microgaming Casino 예스 벳 88 | Microgaming 스포츠분석 | 스코어사이트 Microgaming is the leading 인터넷 바카라 casino software provider, 룰렛 돌리기 게임 offering innovative games, a variety of table games and a

    ReplyDelete
  4. Great article! Your insights are valuable, and it's evident that your team is well-versed in creating tailored solutions. I appreciate the straightforward explanations. If anyone is seeking reliable Custom web development services, they should definitely consider reaching out to our team. Keep up the good work!

    ReplyDelete

Search This Blog