DEV Community

Cover image for js❤️ - Spread Operator
Javi Carrasco
Javi Carrasco

Posted on • Edited on

1 1

js❤️ - Spread Operator

Spread Operator

Este operador permite "extender" los elementos de una colección en varios elementos o parámetros. Veamos algunos usos:

Añadir un elemento a un array sin modificar el original

const a = [1, 2];
const b = [...a, 5]; // [1, 2, 5]
const c = [9, ...a]; // [9, 1, 2]
Enter fullscreen mode Exit fullscreen mode

Concatenar arrays sin modificar los originales

const a = [1, 2];
const b = [5, 9, 10];
const c = [...a, ...b]; // [1, 2, 5, 9, 10]
Enter fullscreen mode Exit fullscreen mode

Clonar un objeto (solo el primer nivel)

const a = { name: "Javi", num: 1 };
const b = { ...a }; // { name: "Javi", num: 1 }
const eq = (a === b); // false
Enter fullscreen mode Exit fullscreen mode

Cambiar un atributo de un objeto sin modificar el original

const a = { name: "Javi", num: 1 };
const b = { ...a, num: 2 }; // { name: "Javi", num: 2 }
Enter fullscreen mode Exit fullscreen mode

Combinar objetos

const a = { name: "Javi", num: 1 };
const jetpack = { altitude: 2000, speed: 850, num: 4 };
const b = { ...a, ...jetpack };
// { name: "Javi", num: 4, altitude: 2000, speed: 850 }
Enter fullscreen mode Exit fullscreen mode

Pasar un array como una lista de argumentos

const tokens = [2022, 1, 3];
const date = new Date(...tokens); // Thu Feb 03 2022...
Enter fullscreen mode Exit fullscreen mode

Siguiente - Destructuring →

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay