Skip to main content

Command Palette

Search for a command to run...

22. MEDIUM | Rest Parameters in JavaScript

This article will talk about rest parameters in javascript.

Updated
2 min readView as Markdown
S
Full-Stack Developer with 4 years' experience, specializing in backend development. Skilled in JavaScript, React, Python, Databases, and AWS. Known for building scalable web apps, leading teams, and maintaining strong client communication. Upskilling in Generative AI.

Rest parameters allow a function to accept an indefinite or variable number of arguments and collect them into a single, real array. They are denoted by three dots (...) followed by a parameter name in the function definition.

Introduced in ES6.

Key Concepts

  • Syntax: The syntax is ...parameterName, where parameterName becomes an array within the function body.

  • Position: A function can have only one rest parameter, and it must be the last parameter in the function definition. This ensures it collects all remaining arguments after any explicitly defined parameters.

  • Purpose: They are used for creating "variadic functions" (functions that accept a variable number of arguments) and are a modern, cleaner alternative to the older arguments object.

  • Real Arrays: Unlike the arguments object, rest parameters are actual Array instances, meaning you can directly use standard array methods like map(), filter(), and forEach() on them.

Example

function func(a, b, c, ...d){
    console.log(a, b, c);
    console.log(d);
};

func(1, 2, 3, 4, 5, 6);
// 1, 2, 3
// [4, 5, 6]

func(1, 2, 3);
// 1, 2, 3
// []

func(1, 2);
// 1, 2, undefined
// []

func();
// undefined, undefined, undefined
// []

Rest Parameters vs. Spread Syntax

Rest parameters use the same ... syntax as the spread syntax, but they are opposites in function.

  • Rest parameters collect multiple elements into a single array (used in function definitions).

  • Spread syntax expands an array (or other iterable) into individual elements (used in function calls or array literals).


Happy reading!