Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Rest Parameters

Master rest parameters to collect multiple arguments into arrays. Write flexible functions.

Why this matters

Rest parameters enable variadic functions that work with any number of arguments. They're essential for building flexible APIs and are the modern replacement for the 'arguments' object.

What are Rest Parameters?

Rest parameters allow a function to accept an indefinite number of arguments as an array. They'redenoted by three dots (...) followed by a parameter name.

Rest parameters are useful when you want a function to work with any number of arguments, replacing the need for the 'arguments' object.

Basic Rest Parameters

// Function accepts any number of arguments
function sum(...numbers) {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}

console.log(sum()); // 0
console.log(sum(5)); // 5
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15

// Rest parameters create an actual array
function printArgs(...args) {
  console.log(args);
  console.log(Array.isArray(args)); // true
  console.log(args.length);
}

printArgs(1, 2, 3);
// [1, 2, 3]
// true
// 3

Rest parameters collect arguments into an array, making it easy to work with variable argument counts.

Rest Parameters with Regular Parameters

You can combine regular parameters with rest parameters. Regular parameters come first, and rest parameters must come last.

Mixing Regular and Rest Parameters

// First parameter is required, rest are optional
function greet(greeting, ...names) {
  let result = greeting + ": ";
  for (let name of names) {
    result += name + " ";
  }
  return result;
}

console.log(greet("Hello")); // Hello: 
console.log(greet("Hello", "Alice")); // Hello: Alice 
console.log(greet("Hello", "Alice", "Bob", "Charlie"));
// Hello: Alice Bob Charlie 

// Multiple regular parameters before rest
function createRecord(id, name, ...tags) {
  return {
    id: id,
    name: name,
    tags: tags
  };
}

console.log(createRecord(1, "Product", "new", "sale", "featured"));
// { id: 1, name: "Product", tags: ["new", "sale", "featured"] }

// Rest must be last
// function test(a, ...b, c) {} // SyntaxError!
// function test(...a, ...b) {} // SyntaxError!

Rest parameters must be the last parameter in a function. Only one rest parameter per function.

Rest Parameters vs Arguments Object

Rest parameters are cleaner and more flexible than the 'arguments' object. Rest parameters create a real array and work with arrow functions.

Rest vs Arguments

// Using arguments object (old way)
function sumOld() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

// Using rest parameters (modern way)
function sumNew(...nums) {
  return nums.reduce((sum, n) => sum + n, 0);
}

console.log(sumOld(1, 2, 3)); // 6
console.log(sumNew(1, 2, 3)); // 6

// Rest parameters work with arrow functions
const multiplyAll = (...numbers) => {
  let result = 1;
  for (let num of numbers) {
    result *= num;
  }
  return result;
};

console.log(multiplyAll(2, 3, 4)); // 24

// arguments doesn't exist in arrow functions
// const add = (...) => console.log(arguments); // ReferenceError

Rest parameters are the modern standard. They work with arrow functions and provide cleaner code.

Practical Uses of Rest Parameters

Rest parameters enable flexible function design for logging, concatenation, array methods, and more.

Real-World Examples

// Logging with variable arguments
function log(level, ...messages) {
  console.log("[" + level + "]", ...messages);
}

log("INFO", "User logged in", "ID: 123");
// [INFO] User logged in ID: 123

// Concatenating arrays
function concatArrays(...arrays) {
  return arrays.reduce((result, arr) => result.concat(arr), []);
}

console.log(concatArrays([1, 2], [3, 4], [5]));
// [1, 2, 3, 4, 5]

// Creating flexible constructors
function Person(...data) {
  if (data.length === 1) {
    this.name = data[0];
  } else if (data.length === 2) {
    this.firstName = data[0];
    this.lastName = data[1];
  }
}

// Function composition
function compose(...fns) {
  return (x) => fns.reduce((result, fn) => fn(result), x);
}

const double = x => x * 2;
const addTen = x => x + 10;
const result = compose(double, addTen)(5);
console.log(result); // (5 * 2) + 10 = 20

Rest parameters enable powerful patterns for flexible, composable functions.

Rest Parameters in Arrow Functions

Rest parameters work perfectly with arrow functions, unlike the 'arguments' object.

  • Arrow functions can use rest parameters (...args)
  • Arrow functions do NOT have access to the 'arguments' object
  • Rest parameters are the preferred way to handle variable arguments in modern JavaScript
  • Rest parameters create a real array with all array methods available
  • Use rest parameters instead of 'arguments' for cleaner, more maintainable code

Common Mistakes

  • Putting rest parameters before regular parameters: Rest parameters must come LAST in the parameter list. Use: (a, b, ...rest), not (...rest, a, b)
  • Using multiple rest parameters: A function can only have ONE rest parameter. (...a, ...b) is invalid.
  • Trying to use arguments in arrow functions: Arrow functions don't have 'arguments'. Use rest parameters (...args) instead.

FAQ

What are rest parameters?

Rest parameters (...args) allow a function to accept any number of arguments and collect them into an array.

What's the difference between rest parameters and the arguments object?

Rest parameters create a real array and work with arrow functions. The arguments object is array-like and doesn't work in arrow functions.

Can I have multiple rest parameters?

No, a function can only have one rest parameter, and it must be the last parameter.

Can I use rest parameters with named parameters?

Yes, you can mix regular parameters with rest parameters. Named parameters must come first: (a, b, ...rest)