JavaScript - Rest Parameters

Overview

Estimated time: 15–25 minutes

Use rest parameters to capture a variable number of arguments into an array.

Learning Objectives

  • Declare rest parameters and iterate them.
  • Understand differences from arguments.

Prerequisites

Examples

function sum(...nums) {
  return nums.reduce((a,b) => a + b, 0);
}
sum(1,2,3); // 6

function tag(strings, ...values) { /* tagged template rest */ }

Common Pitfalls

  • Rest parameter must be the last parameter.
  • Rest collects into a real array (unlike arguments).