1

Looking for more details on what exactly is happening when following is executed:

    function useArray(){
        var args = [].slice.call(arguments)
        console.log(args)
    }

How come slice being a function with 3 parameters (source array, start and end positions to copy) threats arguments correctly? Method call needs correct value of first argument as this but it seems arguments gets turned into Array object?

And why this doesn't work:

var args = [].slice(arguments)

1 Answer 1

1

We're using [].slice to get at the Array::slice method. arguments doesn't have a slice() of its own, but it is array-like.

Although it's a member of Array, slice() will work well enough on array-like objects -- things that have .length and can be indexed with [0..n].

slice() with no parameters returns a copy of the entire array. Its arguments are both optional.

So it's as if arguments had a slice() method, and we called arguments.slice() to get a copy of it (as an array).

[].slice(arguments) is just calling Array::slice() on an empty array, with arguments as the begin parameter, which makes no sense since begin (if present) should be a number.

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

2 Comments

Thank you very much for detailed explanation. It is clear now why [].slice(arguments) returns empty array. One more thing to double-check though. Am I right, saying that [].slice.call(arguments) passes object arguments as the receiver of the call, that call() method of function object is supposed to have as the first argument?
If I read that correctly, yes. It's as if slice was temporarily a member of arguments -- arguments would be this within that slice call.

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.