2

Historically, we had to do:

var args = Array.prototype.slice.call(arguments)
fn.apply(this, args);

to grab actual function call arguments and pass them to Function.prototype.apply. However, since some time, I can see that arguments object does have slice method available, hence above snippet is not required anymore.

The question is - when did it change, what was it, a specification update?


edit: I was unclear above... I mean that fn.apply(this, arguments) does work (I checked in latest chrome and firefox):

function add(a,b){
  return a + b;
}

function whatever(){
  return add.apply(null, arguments)
}

whatever(2,3) // 5

in other words, arguments can be now used within apply directly. Some time ago, it didn't work, it had to be passed to Array.prototype.slice.apply as above.

11
  • 1
    Actually it is now easier. Array.from(arguments) with new ES2016 :) Commented Jan 26, 2017 at 17:46
  • @TolgahanAlbayrak cool, but the question is different ;) Commented Jan 26, 2017 at 17:47
  • 1
    There's no arguments.slice() for me in Firefox. Commented Jan 26, 2017 at 17:48
  • 1
    However, this loses its utility in ECMA6, with the advent of the Rest (splat) operator. Commented Jan 26, 2017 at 17:50
  • 3
    It is not the case that arguments is an array. It's just that those methods work for array-like objects: objects with a .length property and properties with integer names. Commented Jan 26, 2017 at 17:54

2 Answers 2

2

It isn't.

Try the following:

var foo = function() {
  console.log(Object.prototype.toString.call(arguments)); 
};

foo(); // [object Arguments]

console.log(Object.prototype.toString.call([])); // [object Array]

Note that the difference between arrays and objects is a little fuzzy in JS-land:

var foo = { "0": 1, "1": 2 };
Object.defineProperty(foo, "length", {
  value: 2
});

foo will now work with a surprising number of array methods using call, apply, etc.

Sign up to request clarification or add additional context in comments.

Comments

0

No it didn't.

According to MDN

The arguments object is an Array-like object corresponding to the arguments passed to a function.

Example: We want to return the arguments passed to function as an array

Below code throws error because we are directly calling slice method on arguments Array-like object.

function fun(){
    // throws error arguments.slice is not function
    return arguments.slice(0); 
}

Below works expected as we are converting Array-like object to Array

function fun(){
    // returns the arguments as array
    return Array.prototype.slice.call(arguments, 0)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.