DEV Community

Cover image for ES6: Parámetros REST en Javascript
Cristian Fernando
Cristian Fernando

Posted on

5 1

ES6: Parámetros REST en Javascript

¿Qué es un parámetro de tipo REST?

Los parámetros de tipo REST son una nueva funcionalidad añadida al lenguaje en la especificación ES6. Se aplican en funciones (tradicionales o anónimas) y permite recibir n número de parámetros.

Sintaxis

function test(a,b, ...c){
//cuerpo de la función
}
// ...c es un parámetro de tipo REST
Enter fullscreen mode Exit fullscreen mode

Los 3 puntos suspensivos dentro de la zona de parámetros de una función indican un parámetro de tipo REST

c es un arreglo, por ende podemos usar cualquier método útil para arreglos: map(), filter(), reduce(), etc.

Como siempre todo esto se comprende mejor con ejemplos prácticos:

Imaginemos que queremos hacer una función que nos sume 2 números, se vería más o menos así:

let sumar = (a,b) => a+b;
console.log(sumar(5,6))
//salida: 11
Enter fullscreen mode Exit fullscreen mode

Ahora como podríamos modificar nuestra función sumar() para que podamos sumar cualquier cantidad de números y no solo limitarnos a 2, para ello, podemos usar un parámetro de tipo REST de la siguiente manera:

let sumar = (...numeros) => numeros.reduce((a,b) => a+b);
console.log(sumar(5,6,9)) //20
console.log(sumar(5,6,9,12)) //32
console.log(sumar(5,6)) //11
Enter fullscreen mode Exit fullscreen mode

numeros es un arreglo.

Usando un parámetro de tipo REST y el método reduce() podemos llegar a sumar n numeros usando nuestra función.

Ahora imaginemos que necesitamos crear una función que determine cuál es el mínimo numero de una lista

function max(...numeros){
  let max = numeros[0];
  for(let i=1; i<= numeros.length; i++){
    if(numeros[i]>max){
      max = numeros[i];
    }
  }
  return max;
}
console.log(max(5,9,3));// 9
console.log(max(10,20,30));// 30
console.log(max(5,8,10,100,-1,8,70,50,1598,-9,50,71)); //1598
console.log(max(5));// 5
console.log(max());// undefined
Enter fullscreen mode Exit fullscreen mode

Como pueden ver funciona muy bien, pero tenemos un pequeño problema cuando llamamos a la función sin parámetros, para solucionar esto podemos hacer una pequeña validación:

function max(...numeros){
  if(!numeros.length){
    return("Necesita poner parametros")
  }
  let max = numeros[0];
  for(let i=1; i<= numeros.length; i++){
    if(numeros[i]>max){
      max = numeros[i];
    }
  }
  return max;
}
console.log(max());// "Necesita poner parametros"
Enter fullscreen mode Exit fullscreen mode

Teniendo en cuenta que javascript soporta parámetros por defecto podríamos mejorar nuestro ejemplo:

function max(max = 0 ,...numeros){
  for(let i=0; i<= numeros.length; i++){
    if(numeros[i]>max){
      max = numeros[i];
    }
  }
  return max;
}
console.log(max(5,9,3));// 9
console.log(max(10,20,30));// 30
console.log(max(5,8,10,100,-1,8,70,50,1598,-9,50,71)); //1598
console.log(max(5));// 5
console.log(max());// 0
Enter fullscreen mode Exit fullscreen mode

Un detalle a tomar en cuenta es que los parámetros REST deben incluirse al final, por ejemplo, si hiciera lo siguiente, tendría un error:

//incorrecto
function max(...numeros, max = 0 ){
//cuerpo de la función
}

//correcto
function max(max = 0 , ...numeros){
//cuerpo de la función
}
Enter fullscreen mode Exit fullscreen mode

Referencias 👌


Conclusiones

  • Los parámetros REST permiten incorporar n parámetros a nuestras funciones.
  • Los parámetros REST son arreglos, por ende, podemos usar varios métodos disponibles para su manipulación.
  • El orden de los parámetros importa.

gif

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

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

Okay