6

I have an Array const arr = new Array(100).

And I set

arr[0] = 'A'
arr[49] = 'X'

When destructuring the 1st element, I can do it like:

let [first] = arr

How the statement would be like if I want to access to the 50th element by destructuring expression?

8
  • It would best be let x = arr[49] Commented May 17, 2019 at 8:28
  • @bambam He's talking about destructuring Commented May 17, 2019 at 8:29
  • I know, but you wouldn't use destructuring to get the 50th element @NullDev Commented May 17, 2019 at 8:30
  • Please note it's destructuring, not destructing. Commented May 17, 2019 at 8:31
  • 4
    I ran into the issue because ESLint notifies me to use destructuring while I am going to use let key = arr[3]. Commented May 17, 2019 at 8:44

1 Answer 1

14

You can grab the element using object destructuring, like so:

const arr = Array(50).fill(0).map((_, i) => `Element ${i + 1}`)

const {49: fifty} = arr
console.log(fifty)

Sign up to request clarification or add additional context in comments.

3 Comments

can the index by dynamic?
@capr Can you be more specific? Destructuring like this isn't common, just use bracket notation like arr[index].
Dynamic index is covered at stackoverflow.com/q/73886848/2336725

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.