0
0
Svelteframework~5 mins

Optional parameters in Svelte

Choose your learning style9 modes available
Introduction

Optional parameters let you make parts of your component or function flexible. You can choose to provide them or not without causing errors.

When you want a component to work with or without some data.
When a function can do a default action if some info is missing.
When you want to keep your code simple and avoid many versions of the same function.
When you want to provide default values but allow users to change them.
Syntax
Svelte
function greet(name = 'friend') {
  return `Hello, ${name}!`;
}

// In Svelte component props:
<script>
  export let color = 'blue';
</script>

In JavaScript functions, you set optional parameters by giving them default values.

In Svelte, you make component props optional by assigning default values when exporting them.

Examples
This function says hello to a name or to 'friend' if no name is given.
Svelte
function greet(name = 'friend') {
  return `Hello, ${name}!`;
}

console.log(greet());
console.log(greet('Alice'));
This Svelte component shows a size that defaults to 'medium' if not provided.
Svelte
<script>
  export let size = 'medium';
</script>

<p>The size is {size}.</p>
The count prop is optional and starts at 1 if not passed in.
Svelte
<script>
  export let count = 1;
</script>

<button>Clicked {count} times</button>
Sample Program

This Svelte component greets a user. If you don't give a name or greeting, it uses 'Guest' and 'Welcome' by default.

Svelte
<script>
  export let name = 'Guest';
  export let greeting = 'Welcome';
</script>

<h1>{greeting}, {name}!</h1>
OutputSuccess
Important Notes

Always provide default values for optional parameters to avoid undefined errors.

Optional parameters help keep your components flexible and easy to reuse.

Summary

Optional parameters let you skip giving some inputs without breaking your code.

In Svelte, use export let with a default value to make props optional.

In JavaScript functions, assign default values to parameters to make them optional.