last index array javascript
var colors = ["red","blue","green"];
var green = colors[colors.length - 1]; //get last item in the array
last index array javascript
var colors = ["red","blue","green"];
var green = colors[colors.length - 1]; //get last item in the array
how to get first and last element of array in javascript
The rest parameter can only use at the end not anywhere else in the destructuring so it won't work as you expected.
Instead, you can destructor certain properties(an array is also an object in JS), for example, 0 for first and index of the last element for last.
let array = [1,2,3,4,5,6,7,8,9,0]
let {0 : a ,[array.length - 1] : b} = array;
console.log(a, b)
Expand snippet
Or its better way to extract length as an another variable and get last value based on that ( suggested by @Bergi) , it would work even there is no variable which refers the array.
let {0 : a ,length : l, [l - 1] : b} = [1,2,3,4,5,6,7,8,9,0];
console.log(a, b)
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us