Destructuring to get the last element of an array in es6

console.log('last', [1, 3, 4, 5].slice(-1));
console.log('second_to_last', [1, 3, 4, 5].slice(-2));

I believe ES6 could at least help with that:

[...arr].pop()

Given your array (arr) is not undefined and an iterable element (yes, even strings work!!), it should return the last element..even for the empty array and it doesn't alter it either. It creates an intermediate array though..but that should not cost much.

Your example would then look like this:

  console.log(  [...['a', 'b', 'program']].pop() );

It is not possible in ES6/2015. The standard just doesn't provide for it.

As you can see in the spec, the FormalParameterList can either be:

  • a FunctionRestParameter
  • a FormalsList (a list of parametes)
  • a FormalsList, followed by a FunctionRestParameter

Having FunctionRestParameter followed by parameters is not provided.


You can destructure the reversed array to get close to what you want.

const [a, ...rest] = ['a', 'b', 'program'].reverse();
  
document.body.innerHTML = 
    "<pre>"
    + "a: " + JSON.stringify(a) + "\n\n"
    + "rest: " + JSON.stringify(rest.reverse())
    + "</pre>";