javascript / beginner
Snippet
Providing Fallback Values Using Function Default Parameters
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed during invocation. This prevents unexpected undefined references and reduces boilerplate checks inside your event handler functions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
<script>let message = 'Welcome!';function greet(name = 'Guest', excitementLevel = 1) {const punctuation = '!'.repeat(excitementLevel);message = `Welcome, ${name}${punctuation}`;}</script><button on:click={() => greet()}>Greet Default</button><button on:click={() => greet('Alice', 3)}>Greet Alice</button><p>{message}</p>
svelte
Breakdown
1
function greet(name = 'Guest', excitementLevel = 1) {
Defines default values for both name and excitementLevel if arguments are omitted.
2
const punctuation = '!'.repeat(excitementLevel);
Generates exclamation marks based on the numeric parameter.
3
<button on:click={() => greet()}>Greet Default</button>
Triggers greet without arguments, falling back to 'Guest' and excitement level 1.