Array Destructuring

// we have an array with the name and surname
let arr = ["Ilya", "Kantor"]

// Destructuring assignment
let [firstName, surname] = arr;

alert(firstName); // Ilya
alert(surname);  // Kantor
let [firstName, surname] = "Ilya Kantor".split(' ');

// Unwanted elements of the array can also be thrown away via an extra comma:
// First and second elements are not needed
let [, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert(title); // Consul

// We can use it with any iterable, not only arrays:
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);

// We can use any “assignables” at the left side.
let user = {};
[user.name, user.surname] = "Ilya Kantor".split(' ');
let user = {
  name: "John",
  age: 30
};

// Or as a Map:
let user = new Map();
user.set("name", "John");
user.set("age", "30");

// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
  alert(`${key}:${value}`); // name:John, then age:30
}

The Rest ‘…’

let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert(name1); // Julius
alert(rest[0]); // Consul
alert(rest.length); // 2

Default Values

let [firstName, surname] = [];
alert(firstName); // undefined

// Default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"];

alert(name);    // Julius (from array)
alert(surname); // Anonymous (default used)
// Runs only prompt for surname
let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"];

alert(name);    // Julius (from array)
alert(surname); // whatever prompt gets

Object Destructuring