DEV Community

Cover image for JavaScript Rest Parameters: Because Sometimes You Just Need More Args
Athreya aka Maneshwar
Athreya aka Maneshwar

Posted on

12 4 4 4 4

JavaScript Rest Parameters: Because Sometimes You Just Need More Args

Ever found yourself writing a function and thinking, “I don’t know how many arguments this will need... maybe 2, maybe 20?” Well, JavaScript has your back with something called rest parameters.

They're like a magic bag that scoops up all the leftover arguments into a neat array.

Let’s dive into what they are, how to use them, and why they’re awesome.

No pizza arguments here—just code.

The Basics

Rest parameters use the ... syntax to gather extra arguments passed to a function into an array.

function sum(...theArgs) {
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
}

console.log(sum(1, 2, 3));    // 6
console.log(sum(1, 2, 3, 4)); // 10
Enter fullscreen mode Exit fullscreen mode

You can pass in as many arguments as you like, and the function just gobbles them all up.

Syntax Rules (AKA the Fine Print)

  • Only one rest parameter is allowed.
  • It must be the last parameter.
  • No default values or trailing commas allowed after it.

This is valid:

function logThings(a, b, ...others) {
  console.log(others);
}
Enter fullscreen mode Exit fullscreen mode

This will scream at you:

function wrong1(...one, ...two) {}     
function wrong2(...rest, next) {}      
function wrong3(...stuff,) {}          
function wrong4(...stuff = []) {}      
Enter fullscreen mode Exit fullscreen mode

How It Works

Let’s look at a simple example:

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five");
Enter fullscreen mode Exit fullscreen mode

Console output:

a one
b two
manyMoreArgs [ 'three', 'four', 'five' ]
Enter fullscreen mode Exit fullscreen mode

Even if you don’t pass extra values, manyMoreArgs is still a real array:

myFun("one", "two"); 
// manyMoreArgs -> []
Enter fullscreen mode Exit fullscreen mode

Only pass one extra?

myFun("one", "two", "three"); 
// manyMoreArgs -> [ "three" ]
Enter fullscreen mode Exit fullscreen mode

Counting Arguments with Rest

Since rest parameters are just arrays, you can easily use .length:

function fun1(...theArgs) {
  console.log(theArgs.length);
}

fun1();         
fun1(42);       
fun1(1, 2, 3);  
Enter fullscreen mode Exit fullscreen mode

Combine with Regular Params

You can mix normal parameters with rest ones. Example:

function multiply(multiplier, ...theArgs) {
  return theArgs.map((num) => multiplier * num);
}

console.log(multiply(2, 10, 20, 30)); 
Enter fullscreen mode Exit fullscreen mode

Rest vs arguments (Aka The Old Way)

You could use the arguments object… but it's kinda stuck in the past.

function oldWay() {
  const args = Array.from(arguments);
  console.log(args.sort());
}
Enter fullscreen mode Exit fullscreen mode

But arguments is not a real array, so this won’t work:

function nope() {
  arguments.sort();  
}
Enter fullscreen mode Exit fullscreen mode

With rest parameters, you’re already working with a real array:

function sortArgs(...args) {
  return args.sort();
}

console.log(sortArgs(5, 3, 7, 1)); 
Enter fullscreen mode Exit fullscreen mode

Destructuring Rest Params

You can even destructure them, skipping the first few values:

function ignoreFirst(...[, b, c]) {
  return b + c;
}

console.log(ignoreFirst(10, 20, 30)); // 50
Enter fullscreen mode Exit fullscreen mode

TL;DR

✅ Use ...rest when you don’t know how many arguments you’ll get

✅ It's a clean, modern alternative to the arguments object

✅ Works great with array methods like map, sort, forEach

❌ Only one rest param per function

❌ It must come last


I’ve been actively working on a super-convenient tool called LiveAPI.

LiveAPI helps you get all your backend APIs documented in a few minutes

With LiveAPI, you can quickly generate interactive API documentation that allows users to execute APIs directly from the browser.

Image description

If you’re tired of manually creating docs for your APIs, this tool might just make your life easier.

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping

Top comments (4)

Collapse
 
nevodavid profile image
Nevo David

i think stuff like rest parameters is actually super helpful for me - makes me curious, you think the old way of grabbing function args ever made sense or was it always just awkward?

Collapse
 
ngam_vitalisyuh_3161eef2 profile image
Ngam Vitalis Yuh

Great insights, thank you for the knowledge

Collapse
 
lurah profile image
Adrie T

Great to know this. Is there something like **kwargs also in JavaScript?

Collapse
 
danyk2099 profile image
Daniel

Looks good, but why not just use an array as a param?

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

👋 Kindness is contagious

Delve into a trove of insights in this thoughtful post, celebrated by the welcoming DEV Community. Programmers of every stripe are invited to share their viewpoints and enrich our collective expertise.

A simple “thank you” can brighten someone’s day—drop yours in the comments below!

On DEV, exchanging knowledge lightens our path and forges deeper connections. Found this valuable? A quick note of gratitude to the author can make all the difference.

Get Started