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

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay