agosto 15, 2022

¿Qué es un operador spread?

El operador spread en JavaScript es una sintaxis útil para agregar elementos a una matriz, combinar matrices en una más grande, distribuir una matriz dentro de los argumentos de una función y más posibilidades.

// Concatenating arrays and objects
let arr1 = [1,2,3]; 
let arr2 = [4,5]; 
let newArray = [...arr1,...arr2]; 
console.log(newArray);
// Output: [ 1, 2, 3, 4, 5 ] 

// Copying array elements
let arr = ["a","b","c"]; 
let newArray = [...arr]; 
console.log(newArray);
// Output: ["a", "b", "c"]

// Expanding arrays
let arr = ["a","b"]; 
let newArray = [...arr,"c","d"]; 
console.log(newArray);
// Output: ["a", "b", "c", "d"]

// Merging objects
const userBasic = { 
	name: "Jen", 
	age: 22,
}; 
const userMoreInfo = { 
	country: "Argentina", 
	city: "Córdoba", 
}; 
const user = {... userBasic, ... userMoreInfo};
// Output: {  name: "Jen",  age: 22, country: "Argentina", city: "Córdoba" }