Languages
[Edit]
EN

JavaScript - unpack array elements into separate variables

0 points
Created by:
Kevin
797

In this article, we would like to show you how to destructure (unpack) array elements into separate variables in JavaScript.

1. Using array notation

In this section, we use simple array notation to "unpack" array into separate variables by index.

// ONLINE-RUNNER:browser;

var array = ['a', 'b']

var a = array[0];
var b = array[1];

console.log(a); // a
console.log(b); // b

2. Using ES6 destructuring assignment

In this section, we use array destructuring to unpack array items into separate variables by index.

Example 1

// ONLINE-RUNNER:browser;

let [a, b] = ['a', 'b'];

console.log(a); // a
console.log(b); // b

Example 2

// ONLINE-RUNNER:browser;

var array = ['a', 'b'];
var [a, b] = array;

console.log(a); // a
console.log(b); // b

 

See also

  1. JavaScript - array destructuring with rest parameter

References

  1. Destructuring assignment - JavaScript | MDN

Alternative titles

  1. JavaScript - unpacking array elements into separate variables
  2. JavaScript - destructure array elements into separate variables
  3. JavaScript - destructuring array elements into separate variables
  4. JavaScript - assign array values to multiple variables
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join