-1

I am learning ES6 Destructuring

I am getting an error Rest element must be last element

Here is what I have right now

const siblings = ['John','Jack','Amanda','Allie','Bob']

let [firstSiblingName,...middleAllSiblingsName,lastSiblingName] = siblings
console.log(lastSiblingName)

What I want is

firstSiblingName = 'John'
middleAllSiblingsName = ['Jack','Amanda','Allie']
lastSiblingName = 'Bob'

If I remove lastSiblingName then it works, but in that way I cannot get last element separately.

What I am doing wrong , and how can I make it to achieve the required output.

Magnus Melwin
  • 1,509
  • 1
  • 21
  • 32

2 Answers2

0

You can't, not with rest syntax alone - rest will always consume all of the rest of the elements of the array. You'll have to .pop() the last element instead, after extracting the middle elements:

const siblings = ['John','Jack','Amanda','Allie','Bob'];

let [firstSiblingName,...middleAllSiblingsName] = siblings;
const lastSiblingName = middleAllSiblingsName.pop();
console.log(lastSiblingName)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

According to mdn only the last parameter can be a "rest parameter". Instead you can do like this

const siblings = ['John', 'Jack', 'Amanda', 'Allie', 'Bob']

let [firstSiblingName, , , , lastSiblingName] = siblings
console.log(lastSiblingName)
brk
  • 48,835
  • 10
  • 56
  • 78