-
- Notifications
You must be signed in to change notification settings - Fork 4.7k
Closed
Description
Describe the bug
Buttons B and C have identical callbacks, but the generated JS output differs:
// B button_1.__click = (e) => { const index = Number(e.currentTarget.dataset.index); console.log(index); };
// C var on_click = (e, state) => { const i = Number(e.currentTarget.dataset.index); $.set(state, $.get(state) + (i + 1)); }; button_2.__click = [on_click];
This is because the index
variable name is reused inside the callback:
{#each { length: 1 } as _, index} <!-- New callback per-loop --> <button type="button" onclick={() => console.log(index)}>A</button> <!-- New callback per-loop --> <button type="button" data-index={index} onclick={(e) => { const index = Number(e.currentTarget.dataset.index)!; console.log(index); }}>B</button > <!-- Shared callback between loops --> <button type="button" data-index={index} onclick={(e) => { // Variable name has been changed for optimization. const i = Number(e.currentTarget.dataset.index)!; console.log(i); }}>C</button > {/each}
If the loop variables (e.g. index
) are redefined in the first line (e.g. const index =
), they can be optimized.
(Without renaming index
to i
in this case.)
Reproduction
https://svelte.dev/playground/93ce89c9e31248b3947dc23ae54e5992?version=5.36.5
Logs
System Info
-
Severity
annoyance
Metadata
Metadata
Assignees
Labels
No labels