Question regarding rest argument

Check out this code:

function howMany(...args) {
  return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2));
console.log(howMany("string", null, [1, 2, 3], { }));

The console would display the strings You have passed 3 arguments. and You have passed 4 arguments..

How is it that console would display these two as mentioned above? Thanks in advance!

Hi @adil.k ,

function howMany(…args) {

Here, you are looking at a rest perameter (...args). Here the rest perameter is collecting all the (extra) arguments passed to howMany() and storing them inside args. The parameter args is an array that stores each of the ‘unassigned’ arguments passed. This is why you can use Array methods such as length on args.

I suggest that you take a look at the article below:

While at it, I highly recommend that you check out the spread syntax, so that you do not get confused between the two:

The spread operator basically extends an array where a list is expected. So ...[1, 2, 3]' becomes 1, 2, 3’

I still don’t really understand how do we get “You have passed 3/ 4 arguments” line. Why is “null” there for example. What does it do? How do we achieve number 3 and 4? What’s with the empty { } at the end?

This is 3 because it is passed three arguments:

console.log(howMany(0, 1, 2));
                    ↑  ↑  ↑
                    1  2  3

This is 4 because it is passed four arguments:

console.log(howMany("string", null, [1, 2, 3], { }));
                        ↑      ↑        ↑       ↑
                        1      2        3       4

This is 4 because it is passed four arguments:

var a_string = "string";
var a_null = null;
var an_array = [1, 2, 3];
var an_object = {};

console.log(howMany(a_string, a_null, an_array, an_object));
                        ↑       ↑        ↑          ↑
                        1       2        3          4

This is 10 because it is passed ten arguments:

console.log(howMany([ ], { }, 100, "hello", [1], false, { key: "value" }, [ ], 420, true));
                     ↑    ↑    ↑      ↑      ↑     ↑           ↑           ↑    ↑     ↑
                     1    2    3      4      5     6           7           8    9     10

This is 0 because it is passed zero arguments:

console.log(howMany());
1 Like

thx buddy. Perfectly explained!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.