-6

The MDN Web Docs have this example:

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. This allows you to simultaneously unpack the properties and indices of arrays.

const [a, b, ...{ pop, push }] = [1, 2];
console.log(a, b); // 1 2
console.log(pop, push); // [Function pop] [Function push]

What are those pop and push functions and how to use them?

> pop()
Uncaught TypeError: Cannot convert undefined or null to object
    at pop (<anonymous>)
> push(3)
Uncaught TypeError: Cannot convert undefined or null to object
    at push (<anonymous>)
Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
  • 3
    [Push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) and [pop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) from arrays – Rojo Apr 16 '23 at 22:43
  • 4
    This is a confusing example because it disassociates the methods from their normal context. In order to use them you need to provide a valid `this` ie using [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) or [`apply`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply). For example `let arr = []; push.call(arr, 6);`. This isn't useful, but seems to have been included for illustration of accessing properties of a rest parameter. – pilchard Apr 16 '23 at 23:03
  • As the quoted text says, they are "*properties and indices of arrays*". (Besides possibly `length`, they're not very useful though). – Bergi Apr 16 '23 at 23:04

1 Answers1

0

With regular destructuring, you can do:

const obj = {a:3, b:4}
const {a} = obj // equivalent to const a = obj.a

Now consider the following code:

const [a, b, ...rest] = [1, 2];
console.log(a, b, rest); // 1 2 []
const {push, pop} = rest;
console.log(push, pop);

rest will be an array containing the third number onwards. Since there is no third number, rest will be an empty array.

push and pop are functions that can be destructured out of an array object. This explains why const [a, b, ...{ pop, push }] = [1, 2]; will extract the pop and push functions from the empty array produced by the spread syntax.

Since you don't have a reference to the array created by the spread syntax, these methods aren't very useful in the example you gave. As @pilchard points out, to invoke either of those methods, you will need to use call or apply so that this will be set to a particular array instance.

A more useful example would be to get the count of the other elements in the array (that were not individually destructured):

const [a, b, ...{length}] = [1, 2, 3, 4, 5]

console.log(length)
Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27