DEV Community

Cover image for Learning Svelte Part # 5

Posted on


Learning Svelte Part # 5

Arrays & Objects

Hello developers and welcome back to this series about how i am learning Svelte.
In today's post i will explain how to update Arrays and Objects, the update happen reactively when we change values.

Let’s try with an example:

First of all, we’re going to declare a new variable called frameworks.

let frameworks = ["Vue", "React","Angular", "Ember"];
Enter fullscreen mode Exit fullscreen mode

And we will loop trough it, in th HTML section:

{#each frameworks as framework}
Enter fullscreen mode Exit fullscreen mode

Essentially we are creating a new list item for each one out of our Frameworks, the result in our html file:

Html result

Now to demonstrate the reactivity we are going to add another item to our list, let’s say after a 3 seconds delay.

To do that we need a new function:


We would expect now to have the last item added to our list, but it's not the case, we need another step before accomplishing the result.

Svelte it's not able to catch the change yet, so it's not reflected inside the list.

To make Svelte to pick up the change we only need to write another line of code on our function, that it's going to work because we will use an equal operator that it's re-assigning the value of frameworks

The new function:


Now the result is the one expected:
Adde Svelte

Another way to achieve the same result it's using the spread syntax in our variable:

spread operator

This is the equivalent to using "push", also we use the equal operator.

For the Objects it's the same but just a little bit easier:

Object operator

This is it for my weekly update, see you next Sunday, until then you can find me on Twitter

Top comments (3)

ksengine profile image
Kavindu Santhusa

Your title should be something like Reactive Arrays & Objects in Svelte
Because this post looks like

alessandrogiuzio profile image

Thank you Kavindu, i will be more precise in the next post

ksengine profile image
Kavindu Santhusa • Edited

Another thing use markdown code syntax instead of images.

markdown code syntax

Note: used 3 backticks( ` )