Understanding function arguments

Hello campers,

Here is a piece of code:

function some(args) {
  return args;
}

console.log(some([1,2,3], 5)); // -> [1,2,3]

Could someone please point me out why the args is [1,2,3] but not all of the arguments?

I even do not know what I have to search for to read more and understand how it works.

I will appreciate any help.

you have one single paramenter in the function, which is args, but you are passing in two arguments (the first is the array, the second is the number), so the first argument is assigned to the parameter, but the other argument is not
If you want to access all the arguments you can or use the arguments object

or like this:

function some(...args) { // this is storing all the arguments passed in in an array called args
  return args;
}

console.log(some([1,2,3], 5)); // -> [[1,2,3], 5]
1 Like

Hi,

Thank you for answering!

I was not aware that if I forward ...someName as a function’s argument, then all the arguments will be passed to the array like someName.

While you were answering, I was looking through google and found another solution, which suits me very well for solving the problem I’ve faced:

function some(arg, ...args) {
  return `The first argument is saved to arg - [${arg}] and the rest of the arguments are saved to args - [${args}]`;
}

console.log(some([1,2,3], 5,4,3,2,1)); // -> [[1,2,3], 5]
// -> "The first argument is saved to arg - [1,2,3] and the rest of the arguments are saved to args - [5,4,3,2,1]"
1 Like

If you were using variables you would assign

var arg1 = [1,2,3];
var arg2 = 5;

likewise when you do some([1,2,3], 5) you’re sending 2 values to your function so it must have 2 variables to assign those values, example function some(arg1, arg2).

The same applies if you want 3, 10 or 50 arguments, you would need to add the same number of arguments to your function.

Alternative you can use the spread operator as stated by @ilenia , the arguments variable or like you stated to have access to every argument.

note that this uses too the rest operator! note though that you can only use the rest operator on the last parameter of the function

more on the rest parameters here:

2 Likes

Hi,

Thank you too.

As far as I understand if I do like this:

or

then the count of arguments will be hardcoded and some of them will be missed, if their count will be increased.

I need more flexible solution, cause I do not know the count of the arguments, but I only know that the first one is an array and all the others are some numbers.

1 Like

For those scenarios spread operator like @ilenia mentioned and like you did in your example

Yeees! :pray:

Rest parameters syntax is the thing I was not aware of yet!

@ilenia and @daspinola thank you for joining the conversation!

1 Like