0

Does anyone know why using console.log inside of a function returns a list instead of the intended array?

function intToArray() {
  var array = [];
  for (var i = 0; i < arguments.length; i++)
    array.push(arguments[i]);
  return array;
}

function printArray() {
  console.log(intToArray(arguments));
}

console.log(intToArray(1,2,3,3,4,4,5,6,7,8,8,9));
// [1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 8, 9]

printArray(1,2,3,3,4,4,5,6,7,8,8,9);
// [0:  {0: 1, 1: 2, 2: 3, 3: 3, 4: 4, 5: 4, …}]
Devon Luongo
  • 127
  • 1
  • 2
  • 11
  • 2
    Possible duplicate of [Passing arguments forward to another javascript function](http://stackoverflow.com/questions/3914557/passing-arguments-forward-to-another-javascript-function) – Ziki Nov 10 '15 at 19:53

1 Answers1

1

In first case you pass multiple arguments to intToArray:

intToArray(1, 2, ...)

In the second case you pass a single argument:

intToArray(arguments);

That's more equivalent to intToArray([1,2,3]).

In both cases an array is printed, but with different number of elements.

If you want to pass a long all arguments, see Passing arguments forward to another javascript function.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • The functions do not accept input parameters, so it is irrelevant what is passed to them. – Alex Nov 10 '15 at 20:03
  • 3
    @Jaco: You can pass as many or as few arguments to a function in JavaScript, no matter its formal parameters. Simplified example: `function foo() { alert(arguments[0]); }; foo('hello');`. `arguments` is a special variable in every function that is a collection of all arguments (who would have though!) passed. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments for more info. – Felix Kling Nov 10 '15 at 20:04
  • Got it. Thanks Felix! – Devon Luongo Nov 10 '15 at 22:54