ecmascript-6destructuring

Destructuring to get the last element of an array in ES6


In CoffeeScript, this is straightforward:

coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'

Does ES6 allow for something similar?

> const [, b] = [1, 2, 3]
'use strict'
> b  // it got the second element, not the last one!
2
> const [...butLast, last] = [1, 2, 3]
SyntaxError: repl: Unexpected token (1:17)
> 1 | const [...butLast, last] = [1, 2, 3]
    |                  ^
    at Parser.pp.raise (C:\Users\user\AppData\Roaming\npm\node_modules\babel\node_modules\babel-core\node_modules\babylon\lib\parser\location.js:24:13)

Of course I can do it the ES5 way -

const a = b[b.length - 1]

But maybe this is a bit prone to off-by-one errors. Can the splat only be the last thing in the destructuring?


Solution

  • 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.