0

Could anyone give a detailed explanation of what each term in this line of code actually does? I know this is to convert the arguments object into a real Array but I don't understand how it does.

   var args = (arguments.length === 1?[arguments[0]]:Array.apply(null, arguments));
Payam Mesgari
  • 953
  • 1
  • 19
  • 38
  • Wherever you found that code, throw it away. As far as possible. And use an idiomatic [standard approach](http://stackoverflow.com/q/960866/1048572) instead. – Bergi Feb 25 '16 at 18:02
  • Which of the terms exactly are unclear? – Bergi Feb 25 '16 at 18:03
  • Why??? That's a harsh reaction to the code. I don't understand the following part: arguments.length === 1?[arguments[0]]: – Payam Mesgari Mar 01 '16 at 09:04
  • If the `arguments` object has a length of `1` (exactly one argument), then it creates an array literal with that argument as the only element, else …. – Bergi Mar 01 '16 at 15:39

1 Answers1

-1
function someFunc() {
    var args = Array.prototype.slice.call(arguments);
    return args;
}
someFunc(1,2,3);  //[1, 2, 3]

The arguments object is an array-like object (not an array) local to every function and contains an entry for each argument passed into the function.

In the above, we use Array.prototype to create an instance of an array. It could also be written this way var args = [].slice.call(arguments);.

Then we use the slice() method. Slice can be used for array-like objects (in this case our arguments object) as long as you bind the method to the object. For binding in this case, we use call(). You could also use other binding functions such as apply().

The call() method takes in the arguments object, which is the this value provided for slice().

It's worth noting that in EcmaScript 2015 this can be done in a simpler way using Rest parameters and the spread operator. The following is the ES2015 equivalent:

function someFunc(...args) {
    return args;
}
someFunc(1,2,3);  //[1, 2, 3]
Maverick976
  • 528
  • 1
  • 4
  • 11
  • While everything you said is correct, and demonstrates the proper way to do this, your post does not answer the question. – Bergi Feb 25 '16 at 20:55
  • I started putting together my answer before the OP edit, which added the code example. Because I didn't have that context, I demonstrated a simple example on how to create an array from an arguments object. – Maverick976 Feb 25 '16 at 22:36
  • Thank you Maverick976 for the answer and explanation, but as already stated the code came later, my excuses, and the answer is different. – Payam Mesgari Feb 26 '16 at 16:48