57

How to get array using destructing?

const num = [1,2,3,4,5];
const [ first ] = num; //1

console.log(first) I'm able to get 1, but when I try to do const [ null, second ] = num it has expected token error. How to get 2nd item of num array?

Alan Jenshen
  • 3,159
  • 9
  • 22
  • 35

2 Answers2

133

You can skip parametr name just by putting comma

var num = [1, 2, 3, 4, 5];
var [ ,x] = num;

for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Ignoring_some_returned_values section Ignoring some returned values

yuriy636
  • 11,171
  • 5
  • 37
  • 42
Piotr Pasieka
  • 2,063
  • 1
  • 12
  • 14
  • How to assign the full array to a new value? E.g., `const [x, y :as pos] = queue.shift();` (where `x` would be 1, `y` would be 2 and `pos` would be `[1, 2]`? (Only `:as` does not exist in Javascript) – user2609980 Oct 07 '22 at 08:21
46

As alternative you can use object destructuring because arrays are objects:

var {1: second} = num;

But simply omitting the first element as Piotr suggests in their answer is a bit cleaner in this particular case.

See also Object destructuring solution for long arrays?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143