https://lenguajejs.com/javascript/modulos/que-es-esm/
https://www.w3schools.com/react/react_es6_modules.asp
https://developer.mozilla.org/es/docs/Web/JavaScript/Guide/Modules
function extremos(cadenas) {
let larga = cadenas[0];
let corta = cadenas[0];
for (let cadena of cadenas) {
if (cadena.length > larga.length) {
larga = cadena;
}
if (cadena.length < corta.length) {
corta = cadena;
}
}
return [corta, larga];
}
let alumnos = ["Ana", "Rodrigo", "Pepe"];
let [corto, largo] = extremos(alumnos);
console.log(corto);
console.log(largo)
let [mascorta] = extremos(alumnos);
let [, maslarga] = extremos(alumnos);
console.log(mascorta);
console.log(maslarga);
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
}
const myUpdatedVehicle = { ...myVehicle, ...updateMyVehicle }
console.log(myUpdatedVehicle)
const nuevo = { ...myUpdatedVehicle, color: "pink" };
console.log(nuevo);
const noDesestructurado = { myVehicle, updateMyVehicle }
console.log(noDesestructurado)
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [numbersOne, numbersTwo];
console.log(numbersCombined);
let miObjeto={nombre:"Ana",edad:20,mail:"a@a.com",apellido:"Pi"};
console.log(miObjeto)
let {a,b,c}=miObjeto;
console.log(a,b,c)
let aa,bb;
[aa,bb]=[1,2,3];
console.log(aa,bb)
let nombre,edad;
// {nombre,edad}=miObjeto; Esto da error
({nombre,edad}=miObjeto); // Hay que ponerlo enter paréntesis
console.log(nombre,edad)
// o usar let
let {mail}=miObjeto;
console.log(mail)
let {mail:email}=miObjeto; // recupero la propiedad mail pero la renombro a email
console.log(email)
let {sueldo=1000}=miObjeto; // Como sueldo no existe coge el valor por defecto
console.log(sueldo)
let propiedadABuscar='apellido';
let {[propiedadABuscar]:prop}=miObjeto; // Siempre tenemo que poner un 'alias', en este caso prop
console.log(prop);
function saludo(nombre,apellidos){
console.log("Hola "+nombre+" "+apellidos);
}
saludo(miObjeto.nombre,miObjeto.apellido);
function saludoDesestructurado({nombre,apellido}){
console.log("Hola "+nombre+" "+apellido);
}
saludoDesestructurado(miObjeto);
The JavaScript destructuring assignment syntax is expressive, compact and more readable that makes it possible to “destructured” (upwarp) values from arrays or properties from objects, into different variables.
[a, b] = [50, 100]; console.log(a); // expected output: 50 console.log(b); // expected output: 100 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(rest); // expected output: [30,40,50]
Array destructuring is very much similar and straight forward, you can use an array literal on the left-hand-side of an assignment expression. Each variable name on the array literal maps to the corresponding item at the same index on the destructured array.
let foo = ['one', 'two', 'three']; let [red, yellow, green] = foo; console.log(red); // "one" console.log(yellow); // "two" console.log(green); // "three"
You can assign a variable value via destructuring separate from the variable’s declaration. For example:- first, you declare the variables then you assign separately.
// declare the variables let a, b; // then you assign separately [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2
You can also set a default value if the unpacked value is undefined
let a, b; // setting default values [a = 5, b = 7] = [1]; console.log(a); // 1 console.log(b); // 7
In the above example, we are setting the default values to a and b. In that case if a or b values are undefined it will assign default values 5 to a and 7 to b
It is possible to swap two variables in one destructuring expression. Isn’t that cool?
let a = 1; let b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1
If you want to swap variables without destructuring it is going to require a temporary variable or XOR swap algorithm but with destructuring

Also Read: All you need to know about swapping two variables in JavaScript
Yes, it is possible to destructure on returning an array from a function.
function c() {
return [10, 20];
}
let a, b;
[a, b] = c();
console.log(a); // 10
console.log(b); // 20
In the above example, c() returns the values [1, 2] as its output can be parsed in a single line with using destructuring.
You can also skip some returned values that are not useful for you. For example:-
function c() {
return [1, 2, 3];
}
let [a, , b] = c();
console.log(a); // 1
console.log(b); // 3
In rare cases, if you want to ignore all values.
[,,] = c();
Yes, I know this is not going to happen ever, but as this is a complete guide I have to tell you everything.
When you are using array destructuring you can assign remaining part of an array to a single variable.
let [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3]
Be careful to trailing comma syntax error, It will occur if trailing comma is used on the left-hand side with a rest element:
let [a, ...b,] = [1, 2, 3]; // SyntaxError: rest element may not have a trailing comma
To read more about Rest operator: Understanding The Rest Operator In Javascript
Like objects, you can also do nested destructuring with arrays. Here is an example below
const color = ['#FF00FF', [255, 0, 255], 'rgb(255, 0, 255)']; // Use nested destructuring to assign red, green and blue const [hex, [red, green, blue]] = color; console.log(hex, red, green, blue); // #FF00FF 255 0 255
let x = {y: 22, z: true};
let {y, z} = x;
console.log(y); // 22
console.log(z); // true
You can assign variables using destructuring without separating it from its declaration. It means you don’t have to create a x variable in the above example.
let y, z;
({y, z} = {y: 1, z: 2});
Note: The parentheses
( ... )around the assignment statement are required when using object literal destructuring assignment without a declaration.
{a, b} = {a: 1, b: 2}is not valid stand-alone syntax, as the{a, b}on the left-hand side is considered a block and not an object literal.However,
({a, b} = {a: 1, b: 2})is valid, as isvar {a, b} = {a: 1, b: 2}Your
( ... )expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.Source MDN
You can also change the name of variables while using object destructuring like an example below:-
let o = {p: 22, q: true};
let {p: foo, q: bar} = o;
console.log(foo); // 22
console.log(bar); // true
For example, var {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo.
You can also set a default value if the unpacked object value is undefined
let {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5
let {a: aa = 10, b: bb = 5} = {a: 3};
console.log(aa); // 3
console.log(bb); // 5
const metadata = {
title: 'Scratchpad',
translations: [
{
locale: 'de',
localization_tags: [],
last_edit: '2014-04-14T08:43:37',
url: '/de/docs/Tools/Scratchpad',
title: 'JavaScript-Umgebung'
}
],
url: '/en-US/docs/Tools/Scratchpad'
};
let {
title: englishTitle, // rename
translations: [
{
title: localeTitle, // rename
},
],
} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
You can compute a property name while changing its name using object destructuring.
let key = 'z';
let {[key]: foo} = {z: 'bar'};
console.log(foo); // "bar"
In the above example, we computed the key variable and change its name to foo
Array and objects can be combined in Destructuring.
const props = [
{ id: 1, name: 'Fizz'},
{ id: 2, name: 'Buzz'},
{ id: 3, name: 'FizzBuzz'}
];
const [,, { name }] = props;
console.log(name); // "FizzBuzz"
Syntax is the same for all destructuring assignment, but on the left-hand side of the assignment to define what values to unpack from the sourced variable. For Example:-
let x = [1, 2, 3, 4, 5]; let [y, z] = x; console.log(y); // 1 console.log(z); // 2
If you liked it please comment and share.
<button id="boton">Pincha para saber algo más los perros</button> <h1 id="frase"></h1> <script src="js/ejercicio4.js"></script>
// Enlazar el click del botón a mi código onclick, addeventlistener
document.getElementById("boton").addEventListener("click", function () {
// En el click: llamar a la url https://dog-api.kinduff.com/api/facts
// ¿Cómo? con la chuleta
// Una vez tengo la información:
fetch("https://dog-api.kinduff.com/api/facts")
.then(response => response.json())
.then(resultado => {
// 1) Recuperar la frase
// 2) Ponerla en el html
let frase = resultado.facts[0];
document.getElementById("frase").innerHTML = frase;
})
})
<h1 id="name"></h1>
<h2 id="email"></h2>
<img src="" id="foto"/>
<script src="js/usuariorandom.js" ></script>
fetch("https://randomuser.me/api")
.then(response => response.json())
.then(resultado => {
// Aqui 'resultado' tiene ya el json convertido a variable, la podemos usar
console.log(resultado);
// Llamo a una función con el usuario devuelto
pintaUsuario(resultado.results[0]);
})
function pintaUsuario(usuario) {
let nombre=document.getElementById("name");
let email=document.getElementById("email");
let foto=document.getElementById("foto");
nombre.innerHTML=Object.values(usuario.name).join(" ");
email.innerHTML=usuario.email;
foto.src=usuario.picture.large;
}
// El formato JSON me permite convertir cualquier variable JS en una cadena
// un array es una cadena con corchetes y los elementos "[1,2,3]"
// un objeto es una cadena con llaves y las propiedades entre comillas
// {"nombre":"Juan","apellidos":Pi}
// cualquier combinación no es más que combinar lo anterior
// {"nombre":"Juan","apellidos":Pi, "notas":[1,2,3]}
// De variable a cadena con JSON.stringify
// De cadena a variable con JSON.parse
let alumnos=["Ana","Eva","Pep"]; // Esto es un array
let alumnosJSON=JSON.stringify(alumnos); // Esto es una cadena
console.log(alumnos);
console.log(alumnosJSON);
// De la cadena puedo volver a obtener el array
let alumnosCopia=JSON.parse(alumnosJSON);
console.log(alumnosCopia); // Es un array
let clase={nombre:"Aula 1",capacidad:30,alumnos:["Ana","Eva","Juan"]};
let claseJSON=JSON.stringify(clase);
console.log(clase); // Esto es un objeto
console.log(claseJSON); // Esto es un string
let claseCopia=JSON.parse(claseJSON);
console.log(claseCopia); // Esto es un objeto de nuevo
<input id="nombre" type="text"/>
let nombre = document.getElementById("nombre");
nombre.oninput = function () {
localStorage.setItem("nombre", this.value);
}
let nombreAlmacenado = localStorage.getItem("nombre");
if (nombreAlmacenado) {
nombre.value = nombreAlmacenado;
}
// Guardar información que se mantenga aunque actualicemos la página
// cookies es una manera pero están obsoletas
document.cookie="nombre=juan";
// La mejor manera actualmente es con localStorage
// Añado una propiedad 'nombre' con el valor 'juan'
localStorage.setItem("nombre","juan");
// Recupero ese valor
console.log(localStorage.getItem("nombre"));
// Elimino la propiedad (y, por supuesto, su valor)
localStorage.removeItem("nombre")
// Limpio todo el localstorage
localStorage.clear();
document.addEventListener('DOMContentLoaded', () => {
launch();
});
const launch = () => {
viewArray('joana');
};
viewArray = (name) => {
const arrayName = ['pere', 'marti', 'joana', 'ricard', 'ramon', 'judit'];
let key = 0;
const arrayView = setInterval(() => {
if (key === arrayName.length) {
clearInterval(arrayView);
console.log(`No s'ha trobat l'usuari`);
} else {
console.log(arrayName[key]);
if (arrayName[key] === name) {
clearInterval(arrayView);
console.log(`S'ha trobat l'usuari: ${name}`);
}
key++;
}
}, 3000);
};
// Dentro de JS pueden suceder errores
// Hay una manera de gestioner errores
// try{...}catch(err){...}
let producto = {
nombre: "Tuerca",
precio: {
PVP: 50,
reducido: 20
}
}
let producto2 = {
nombre: "Tuerca"
}
// Intenta ejecutar el código siguiente
try {
console.log(producto.nombre)
console.log(producto.pecio.PVP)
// Si hay algún error no petes, entra en el catch
} catch (err) {
// Dentro del catch tenemos el parámetro 'err' con la información del error
console.log(err.message);
console.log(err);
} finally {
console.log("Esto se ejecuta siempre");
}
console.log("Hola")
console.log(sumaPreciosOk([producto, producto2]));
// Esto lanza un error porque accedemos a una propiedad que no existe
function sumaPrecios(productos) {
let suma = 0;
for (let producto of productos) {
suma += producto.precio.PVP;
}
return suma;
}
// Aquí lo hacemos bien: esto no interrumpe el programa
function sumaPreciosOk(productos) {
try {
let suma = 0;
for (let producto of productos) {
suma += producto.precio.PVP;
}
return suma;
} catch {
return 0; // podría devolver undefined
}
}
console.log(suma(8));
try{
console.log(suma(-8));
}catch(err){
console.log(err.message)
}
// lanzar errores propios
function suma(numero) {
if(numero<0 || numero>10000){
throw new Error("Número fuera de margen");
}
let suma = 0;
for (let i = 0; i < numero; i++) {
suma += i;
}
return suma;
}