Accessing Multiple Arguments

I'm trying to create a function for two or more parameters. However I don't understand why for sym([1, 2, 3], [5, 2, 1, 4]);

function sym(args) {
  return args;
}

only return [1, 2, 3]

but

 function sym(args) {
  return args;
 }

returns { 0: [ 1, 2, 3 ], 1: [ 5, 2, 1, 4 ] }.

and

function sym(args) {
 args = arguments;
 console.log(args);
}

returns { 0: [Circular], 1: [ 5, 2, 1, 4 ] }

2 answers

  • answered 2018-10-22 13:03 Mosè Raguzzini

    There are various way to write & destructure, IE:

    sym([[1,2,3], [1,2,3,4,5]]);
    
    function sym([arg1, arg2]) {
     console.log(arg1,arg2);
    }
    
    or
    
    function sym(args) {
     console.log(args);
    }

  • answered 2018-10-22 13:03 Benjamin Gruenbaum

    You are defining a function with a single argument called args. What you are looking for is called variadic arguments (or variadic parameters) which means "0 or more arguments".

    Either use rest parameters:

    function sym(...args) {
      return args;
    }
    

    Or if you're using an old version of JavaScript use arguments:

    function sym() {
      return Array.from(arguments);
    }
    

    Your last example is quite beautiful actually. When you do args = arguments (except in strict mode) you are modifying arguments implicitly and giving it a reference to itself (hence the [circular]). I warmly recommend strict mode to avoid these quirks.