Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify difference between initial value and default value in Svelte tutorial #9078

Closed
kenbankspeng opened this issue Aug 6, 2023 · 3 comments

Comments

@kenbankspeng
Copy link

kenbankspeng commented Aug 6, 2023

Describe the bug

Appreciating the decision to stick with legacy behavior for "initial value" syntax:

export let myProp = "initialValue";

versus true default value syntax:

export let myProp;
$: myProp ??= 'defaultValue';

Could the distinction be made clearer in the Svelte tutorial for default values as it currently teaches that a default value is achieved using the "initial value" syntax?

This difference explains why my TS typing was always complaining that it could not execute functions that were optional props since they could be undefined. And here I am thinking, but they are not undefined since I gave them default values. But typescript knew that those initial values could be over-written back to undefined!!! So now I have to go update all my code.

Reproduction

export let myProp = "initialValue";

Logs

No response

System Info

System:
    OS: macOS 13.3.1
    CPU: (8) arm64 Apple M2
    Memory: 34.16 MB / 8.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.17.0 - ~/Library/pnpm/nodejs_current/bin/node
    npm: 9.6.7 - ~/Library/pnpm/npm
    pnpm: 8.6.6 - ~/Library/pnpm/pnpm
  Browsers:
    Chrome: 115.0.5790.170
    Safari: 16.4
  npmPackages:
    svelte: ^4.1.2 => 4.1.2

Severity

annoyance

@brunnerh
Copy link
Member

brunnerh commented Aug 11, 2023

|| is a boolean operator, calling that "true syntax" is a stretch as you are misusing it and it will misbehave for any values that are coerced to false, e.g. 0 or ''.

Also, the statement should do nothing since it has no assignment.
If anything it should be:

$: myProp ??= 'defaultValue';

@kenbankspeng
Copy link
Author

kenbankspeng commented Aug 11, 2023

Indeed, ??= is preferred to capture the full use case without exceptions.

The primary point being export let myProp = "initialValue"; is not comprehensively a default value but is being taught as such without clarification.

@dummdidumm
Copy link
Member

Closing since in Svelte 5 this is now a fallback value that always kicks in when the parent passes undefined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants