EN
JavaScript - unpack array elements into separate variables
0
points
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