[Javascript] Destructuring array by using object syntax
Since arrays are objects, we can destructure their indexes to easily grab the first and last itmes
const bikes = ['bianchi', 'miele', 'miyata', 'benotto', 'panasonic']
// Grab the first and last item of an array with Object destructuring
const {length, 0: first, [length - 1]: last} = bikes;
console.log(first, last) // bianchi panasonic
You can use length
inside destructuring to access the last item
You can use length
to do calculation to access middle item:
const {length, [Math.floor(length / 2)]: middle} = bikes;
console.log(middle) // miyata