0
0
Svelteframework~5 mins

Rest parameters in Svelte

Choose your learning style9 modes available
Introduction

Rest parameters let you collect many values into one place easily. This helps when you don't know how many inputs you will get.

You want to pass many values to a function without listing each one.
You want to gather extra props in a Svelte component without naming them all.
You want to handle a flexible number of arguments in event handlers.
You want to forward all remaining props to a child component.
You want to simplify working with arrays or objects by grouping leftover items.
Syntax
Svelte
function example(...rest) {
  // rest is an array of extra arguments
}

<script>
  // $$restProps collects undeclared props into an object
</script>

In functions, rest parameters use three dots ... before a name to gather extra arguments into an array.

In Svelte components, $$restProps automatically collects all props that are not explicitly declared with export let.

Examples
This function sums any number of arguments passed in using rest parameters.
Svelte
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}
This Svelte component takes a name prop and collects all other props in $$restProps.
Svelte
<script>
  export let name;
</script>

<p>Hello {name}!</p>
<p>Extra props: {JSON.stringify($$restProps)}</p>
Sample Program

This Svelte component defines a function greet that takes one fixed argument and then any number of names using rest parameters. It joins the names with 'and' and shows the greeting.

Svelte
<script>
  // Function using rest parameters
  function greet(greeting, ...names) {
    return `${greeting} ${names.join(' and ')}`;
  }

  let message = greet('Hello', 'Alice', 'Bob', 'Charlie');
</script>

<h1>{message}</h1>
OutputSuccess
Important Notes

Rest parameters must be the last parameter in a function.

Rest parameters gather arguments into an array, so you can use array methods on them.

In Svelte, rest props help pass unknown or extra props to child components or elements.

Summary

Rest parameters collect many arguments into one array.

They make functions and components flexible with inputs.

In Svelte, rest props help handle extra properties easily.