How does the rest parameter (...args) work in functions?

👨‍💻 Frontend Developer 🟡 Often Asked 🎚️ Easy
#JavaScript #Functions #JS Basics

Brief Answer

The rest parameter (…args) allows a function to accept an unlimited number of arguments as an array. The three dots (…) before the parameter name “collect” all remaining arguments into one array, which is convenient when you don’t know how many arguments will be passed.

// Function with rest parameter
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
 
// Usage
console.log(sum(1, 2, 3));        // 6
console.log(sum(1, 2, 3, 4, 5));  // 15
console.log(sum());               // 0

Full Answer

The rest parameter is like a magical bag that can hold as many items as you want, and it will fit everything! The three dots (…) “collect” all arguments into one array, making it easy to work with them. 🎒

What is a Rest Parameter

The rest parameter is a way to collect all function arguments into one array. It’s denoted by three dots (…) before the parameter name:

Simple Examples

Basic Usage

function showItems(...items) {
  console.log('Items received:', items.length);
  console.log('Items:', items);
}
 
showItems('apple', 'banana', 'orange');
// Items received: 3
// Items: ['apple', 'banana', 'orange']

Mixing with Regular Parameters

function greet(greeting, ...names) {
  return greeting + ', ' + names.join(' and ');
}
 
console.log(greet('Hello', 'John', 'Peter', 'Mary'));
// 'Hello, John and Peter and Mary'

How the Rest Parameter Works

Always Creates an Array

function checkType(...args) {
  console.log(Array.isArray(args)); // true
  console.log(typeof args);         // 'object'
  console.log(args.length);         // number of arguments
}
 
checkType(1, 2, 3); // true, 'object', 3

Must Be Last

// ✅ Correctly — rest parameter at the end
function correct(first, second, ...rest) {
  // ...
}
 
// ❌ Error — rest parameter not at the end
// function wrong(...rest, last) {
//   // SyntaxError!
// }

When to Use the Rest Parameter

For Functions with Variable Number of Arguments

// Mathematical operations
function multiply(...numbers) {
  return numbers.reduce((result, num) => result * num, 1);
}
 
console.log(multiply(2, 3));      // 6
console.log(multiply(2, 3, 4));   // 24

For Creating Universal Functions

// Logging with variable number of arguments
function log(...messages) {
  const timestamp = new Date().toLocaleTimeString();
  console.log(`[${timestamp}]`, ...messages);
}
 
log('User', 'John', 'entered'); 
// '[10:30:15] User John entered'

Common Mistakes

Confusion with Arguments

function oldWay() {
  // arguments — not a real array
  console.log(Array.isArray(arguments)); // false
  // Need to convert: Array.from(arguments)
}
 
function newWay(...args) {
  // args — real array
  console.log(Array.isArray(args)); // true
  args.map(item => console.log(item)); // Can use array methods
}

Incorrect Placement

// ❌ Error — rest not at the end
// function bad(param1, ...rest, param2) { }
 
// ✅ Correctly — rest at the end
function good(param1, param2, ...rest) { }

Simple Rules

  1. …args — collects all remaining arguments into an array 🎯
  2. Last parameter — rest must be the last in the parameter list ⚠️
  3. One rest — a function can have only one rest parameter 📦
  4. Real array — unlike [arguments], rest creates a real array ✅
  5. Flexibility — convenient for functions with variable number of arguments 🔄

The rest parameter is a convenient way to work with functions when you don’t know how many arguments will be passed to them. Modern and easy to use! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪