Skip to content

Optimize callbacks inside each block with loop variable names #16414

@hyunbinseo

Description

@hyunbinseo

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions