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?
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() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With