Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MDN JS Array.prototype.slice.call example explanation

Tags:

javascript

I'm trying to understand how to read the code below (taken from MDN's article on Array.prototype.slice) to understand what happens when it runs.

function list() {
   return Array.prototype.slice.call(arguments);
}

My understanding is that the return statement gets a reference to the Array.protoype.slice method. This leads to my first question, "if this is a reference to the slice method, why doesn't it need to be invoked, e.g. Array.prototype.slice().call(arguments)?"

Assuming that this is a call to the slice method, and since there is no argument being immediately passed into it, my second question is "is JS 'seeing' the call method chained to slice and then trying to resolve a value to pass to slice from the call(arguments) method?"

If this is the case, is this method chaining and is this how JS performs chaining operations: from left to right and when there is no argument explicity passed to a method, it tries to resolve a value from a subsequent method to return implicitily to the "empty" callee on the left? Thanks.

like image 406
lance-p Avatar asked Jul 19 '26 03:07

lance-p


1 Answers

  1. Why doesn't it need to be invoked? — because, as you say, it's a reference, and that's all that's desired. The code wants a reference to the function, not a result returned from calling the function.

  2. Is JS 'seeing' the call method chained to slice and then trying to resolve a value to pass to slice from the call(arguments) method? — well I'm not sure what that means. The reference to the .slice() function is used to get access to the .call() method (inherited from the Function prototype). That function (slice.call) is invoked and passed the arguments object as its first parameter. The result is that slice will be invoked as if it were called like arguments.slice() — which is not possible directly, as the .slice() function isn't available that way.

Overall, what the code is doing is "borrowing" the .slice() method from the Array prototype and using it as if the arguments object were an array.

Sometimes you'll see that written like this:

return [].slice.call(arguments);

It's a little shorter, and it does the same thing (at the expense of the creation of an otherwise unused array instance).

like image 140
Pointy Avatar answered Jul 21 '26 15:07

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!