Spread Operator and Rest Parameters

– English Version –

There are many pages wich explain what the Spread Operator (also know as three dots) and Rest Parameters are.

It is an operator that I really like and I would like to share with you some ways that I use it.

📓 Spread…



– English Version –

There are many pages wich explain what the Spread Operator (also know as three dots) and Rest Parameters are.

It is an operator that I really like and I would like to share with you some ways that I use it.

📓 Spread Operator

let numbers = [1, 2, 3, 4];
console.log( numbers );

// => [ 1, 2, 3, 4 ] (print as array)

When we use the spread operator we get the values ​​independently:

let numbers = [1, 2, 3, 4];
console.log( ...numbers );

// => 1 2 3 4

Add an array to another:

let customers = [ 'Claudia', 'Borja', 'May' ];
let otherCustomers = [ 'Sergio', 'Jose' ];

customers.push( ...otherCustomers );
console.log( customers );

// => [ 'Claudia', 'Borja', 'May', 'Sergio', 'Jose' ]

Concat arrays:

let customers = [ 'Claudia', 'Borja', 'May' ];
let otherCustomers = [ 'Sergio', 'Jose' ];

let concatCustomers = [ ...customers, ...otherCustomers ];
console.log( concatCustomers );

// => [ 'Claudia', 'Borja', 'May', 'Sergio', 'Jose' ]

It also happens with objects:

const userData = {
    name: 'Jesús',
    surname: 'Cano',
    age: 8
}

const userAdrress = {
    address: 'C/ Gran Vía',
    number: 34
}

const data = { ...userData, ...userAdrress };
console.log( data );

// => (Output)
// {
//     name: 'Jesús',
//     surname: 'Cano',
//     age: 8,
//     address: 'C/ Gran Vía',
//     number: 34
// }

Destructuring on objects:

const userData = {
    name: 'Jesús',
    surname: 'Cano',
    age: 8
}

const userAdrress = {
    address: 'C/ Gran Vía',
    number: 34
}

let myObject = { ...userData, ...userAdrress }; 
let { name, address } = { ...myObject };

console.log( 'Name:', name, 'Address:', address );

// => Name: Jesús Adrress: C/ Gran Vía

Cleaned up repeated elements from an array:

let numbers = [ 1, 2, 2, 3, 3, 4, 5, 6, 6, 6, 6, 7 ];

let mySelect = new Set( numbers );
numbers =  [ ...mySelect ];

console.log( numbers );

// => [1, 2, 3, 4, 5, 6, 7]

📓 Rest Parameters

Spread operator can also be used as a Rest Parameters, rest of the parameters that are passed to a javascript function and form an array.

const person = ( name, ...qualities ) => {

    console.log(`${name}'s qualities are: `);

    qualities.map( quality => {
        console.log( quality );
    });

}

person( 'Jaime', 'Sympathetic', 'Nice', 'Affective', 'Talkative' );

// => (Output)
// Jaime's qualities are: 
// Sympathetic
// Nice
// Affective
// Talkative

As you can see above, the rest parameters must be at the end, otherwise we will get an error.

const sumNumbers = ( ...args ) => {
    return args.filter( e => typeof e === 'number' )
        .reduce( (prev, curr) => prev + curr );
};

const result = sumNumbers( 1, null, 'fullstack', 5, undefined, 2 );

console.log( result );

// => 8

The possibilities are endless 😃

🔍 Recommended reading

Thank you for reading 🙏

🌎 https://sergioturpin.es
📷 Instagram
🐦 Twitter



– Versión en Español –

Hay muchas páginas que explican qué es el Spread Operator (también conocido como operador de los tres puntos) y los Rest Parameters.

Es un operador que me gusta mucho y me gustaría compartir con vosotros alguna de las situaciones que suelo utilizarlo 😊

📓 Spread Operator

let numeros = [1, 2, 3, 4];
console.log( numeros );

// => [ 1, 2, 3, 4 ] (se imprime como un array)

Cuando utilizamos el Spread Operator obtenemos los valores de manera independiente:

let numeros = [1, 2, 3, 4];
console.log( ...numeros );

// => 1 2 3 4

Lo utilizo también para añadir un array a otro:

let clientes = [ 'Claudia', 'Borja', 'May' ];
let otrosClientes = [ 'Sergio', 'Jose' ];

clientes.push( ...otrosClientes );
console.log( clientes );

// => [ 'Claudia', 'Borja', 'May', 'Sergio', 'Jose' ]

Para concatenar arrays:

let clientes = [ 'Claudia', 'Borja', 'May' ];
let otrosClientes = [ 'Sergio', 'Jose' ];

let concatenaClientes = [ ...clientes, ...otrosClientes ];
console.log( concatenaClientes );

// => [ 'Claudia', 'Borja', 'May', 'Sergio', 'Jose' ]

Lo suelo utilizar también con objetos:

const datosUsuario = {
    nombre: 'Jesús',
    apellido: 'Cano',
    edad: 8
}

const direccionUsuario = {
    direccion: 'C/ Gran Vía',
    numero: 34
}

const datos = { ...datosUsuario, ...direccionUsuario };
console.log( datos );

// => (Output)
// {
//     nombre: 'Jesús',
//     apellido: 'Cano',
//     edad: 8,
//     direccion: 'C/ Gran Vía',
//     numero: 34
// }

También para desestructuración de objetos:

const datosUsuario = {
    nombre: 'Jesús',
    apellido: 'Cano',
    edad: 8
}

const direccionUsuario = {
    direccion: 'C/ Gran Vía',
    numero: 34
}

let miObjeto = { ...datosUsuario, ...direccionUsuario }; 
let { nombre, direccion } = { ...miObjeto };

console.log( 'Nombre:', nombre, 'Dirección:', direccion );

// => Nombre: Jesús Dirección: C/ Gran Vía

Para limpiar elementos repetidos en un array:

let numeros = [ 1, 2, 2, 3, 3, 4, 5, 6, 6, 6, 6, 7 ];

let miSeleccion = new Set( numeros );
numeros =  [ ...miSeleccion ];

console.log( numeros );

// => [1, 2, 3, 4, 5, 6, 7]

📓 Rest Parameters

Spread operator se puede utilizar como un Rest Parameters, el resto de parámetros son pasados a la función javascript y ya con ellos forma un array.

const persona = ( nombre, ...cualidades ) => {

    console.log(`Las cualidades de ${nombre} son: `);

    cualidades.map( cualidad => {
        console.log( cualidad );
    });

}

persona( 'Jaime', 'Simpático', 'Agradable', 'Afectivo', 'Charlatán' );

// => (Output)
// Las cualidades de Jaime son: 
// Simpático
// Agradable
// Afectivo
// Charlatán

Como puedes ver, el Rest Parameters está colocado al final, de otra manera nos devolvería un error.

const sumaNumeros = ( ...args ) => {
    return args.filter( e => typeof e === 'number' )
        .reduce( (prev, curr) => prev + curr );
};

const resultado = sumaNumeros( 1, null, 'fullstack', 5, undefined, 2 );

console.log( resultado );

// => 8

Las posibilidades son infinitas 😃

🔍 Lecturas recomendadas

Gracias por leer 🙏

🌎 https://sergioturpin.es
📷 Instagram
🐦 Twitter


Print Share Comment Cite Upload Translate
APA
Sergio Turpín | Sciencx (2024-03-28T10:47:37+00:00) » Spread Operator and Rest Parameters. Retrieved from https://www.scien.cx/2021/11/20/spread-operator-and-rest-parameters/.
MLA
" » Spread Operator and Rest Parameters." Sergio Turpín | Sciencx - Saturday November 20, 2021, https://www.scien.cx/2021/11/20/spread-operator-and-rest-parameters/
HARVARD
Sergio Turpín | Sciencx Saturday November 20, 2021 » Spread Operator and Rest Parameters., viewed 2024-03-28T10:47:37+00:00,<https://www.scien.cx/2021/11/20/spread-operator-and-rest-parameters/>
VANCOUVER
Sergio Turpín | Sciencx - » Spread Operator and Rest Parameters. [Internet]. [Accessed 2024-03-28T10:47:37+00:00]. Available from: https://www.scien.cx/2021/11/20/spread-operator-and-rest-parameters/
CHICAGO
" » Spread Operator and Rest Parameters." Sergio Turpín | Sciencx - Accessed 2024-03-28T10:47:37+00:00. https://www.scien.cx/2021/11/20/spread-operator-and-rest-parameters/
IEEE
" » Spread Operator and Rest Parameters." Sergio Turpín | Sciencx [Online]. Available: https://www.scien.cx/2021/11/20/spread-operator-and-rest-parameters/. [Accessed: 2024-03-28T10:47:37+00:00]
rf:citation
» Spread Operator and Rest Parameters | Sergio Turpín | Sciencx | https://www.scien.cx/2021/11/20/spread-operator-and-rest-parameters/ | 2024-03-28T10:47:37+00:00
https://github.com/addpipe/simple-recorderjs-demo