Course contentsShow
← JavaScript
Lesson 989 of 2,72322. Spread and RestFree lesson

Empty Rest Collections

Handle cases where rest parameters or destructuring collect zero elements gracefully.

Empty Rest Collections

In this lesson, you'll learn how JavaScript handles rest parameters and rest destructuring when there are zero elements left to collect.

What Happens When There's Nothing to Rest?

When you use the rest operator (...) to collect "remaining" elements, JavaScript doesn't throw an error if there's nothing left to collect. Instead, it gracefully assigns an empty array or empty object depending on the context.

Think of it like asking someone to "put all the leftover cookies in a jar." If there are no cookies left, you don't get an error—you just get an empty jar.

Rest Parameters with No Arguments

function greet(first, ...others) {
  console.log(first);
  console.log(others);
}

greet("Alice");
// "Alice"
// []  ← empty array, not undefined

The others parameter becomes an empty array [] because no additional arguments were passed.

Rest in Array Destructuring

const [first, ...rest] = ["only"];
console.log(first); // "only"
console.log(rest);  // []  ← empty array

const [a, b, ...remaining] = [];
console.log(a);         // undefined
console.log(remaining); // []  ← still an empty array

Even when destructuring an empty array, the rest element is always an array—never undefined.

Rest in Object Destructuring

const { name, ...otherProps } = { name: "Bob" };
console.log(name);       // "Bob"
console.log(otherProps); // {}  ← empty object

const { x, ...rest } = {};
console.log(rest); // {}  ← empty object

With objects, an empty rest collection is an empty object {}.

Why This Matters

This consistent behavior means you can safely iterate over or check the length of rest collections without worrying about undefined errors.

Key Takeaway: Rest parameters and rest destructuring always produce empty arrays [] or empty objects {} when there are no elements to collect—never undefined.