// tenemos un array con un nombre y apellido let arr = ["John", "Smith"] // asignación desestructurante // fija firstName = arr[0] // y surname = arr[1] let [firstName, surname] = arr; /* let firstName=arr[0]; let surname=arr[1]; */ console.log(firstName) console.log(surname) console.log(arr) // segundo elemento no es necesario let [nombre, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]; console.log(nombre) console.log(title) let aa = 2; let b = 7; /* let c=a; a=b; b=c; */ // swap de variables usando destructuring [aa, b] = [b, aa] console.log(aa); let user = { name: "John", age: 30 }; // recorrer claves-y-valores con destructuring for (let [key, value] of Object.entries(user)) { console.log(`${key}:${value}`); // name:John, luego age:30 } let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]; console.log(rest); // valores predeterminados let [name = "Guest", apellido = "Anonymous"] = ["Julius"]; let options = { titulo: "Menu", width: 100, height: 200 }; let { width, titulo, height } = options; console.log(titulo) let prueba = { a: 1, b: 2, c: 3, d: 4 }; let { a, ...resto } = prueba; console.log(resto) showMenu(options); showMenu(); function showMenu({ titulo = "Untitled", width = 200, height = 100, items = [] } = {}) { console.log(titulo) }
https://es.javascript.info/destructuring-assignment
https://dev.to/codingnninja/a-simple-guide-to-javascript-destructuring-3o8o
https://davidwalsh.name/spread-operator
https://codeburst.io/a-simple-guide-to-destructuring-and-es6-spread-operator-e02212af5831