Each blocks in Svelte, can't seem to wrap my head around this block of code

<script>
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
let selected = colors[0];
</script>

<h1 style="color: {selected}">Pick a colour</h1>

<div>
{#each colors as color}
<button
aria-current="{selected === color ? 'true' : undefined}"
aria-label={color}
style="background: {color}"
on:click={() => selected = color}
></button>
{/each}
<script>
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
let selected = colors[0];
</script>

<h1 style="color: {selected}">Pick a colour</h1>

<div>
{#each colors as color}
<button
aria-current="{selected === color ? 'true' : undefined}"
aria-label={color}
style="background: {color}"
on:click={() => selected = color}
></button>
{/each}
I understand const colors, I get the each block, but I'm failing to wrap my head around why we're setting selected to colors[0]; and why some of the code in button has color wrapped in {}, and sometimes it doesnt?
4 Replies
b1mind
b1mind2y ago
So you have a current selected to start with the {} 's are for vars/js code so you have like on:click= which is a svelte attribute (like onClick="")
Chris Bolson
Chris Bolson2y ago
I haven't experimented with Svelte yet but {} usually means that the code within should be parsed as JavaScript
CDL
CDLOP2y ago
Ok that makes more sense
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server