If-else and Loops in svelte

series on svelte : part 3

ยท

3 min read

If-else and Loops in svelte

Welcome folks ....i am very excited to find you here , if you are new to svelte then this is the write place for you.

Before we start today,till now, we have completed

So, today we are going to learn syntax of the logics of a programming language used in svelte.

Logics

  • if else conditions
  • Loops

If-else Conditions

There are two places where we will make changes

  • JS part and
  • HTML part

First : condition in JS part is nothing new,its simple if else if blocks and switch cases

Second : HTML part , svelte provides a way to handle condition based rendering of elements i.e either to show or not the particular element depending upon some condition.we will try to understand with the help of a simple example.

let's create a svelte-app as mentioned here

App.svelte looks like this

<script>
    let disp = true;

</script>

<p>Display true </p> // line 1.

If we want to display the line 1 when disp variable is true and hides when disp is false, we have to add some condition to do lets see how we can do it

<script>
    let disp = true;

</script>
{#if disp}
<p>Display true </p> 
{/if}

it works fine , and if we do disp= false then it doesn't display it

Screenshot from 2021-09-24 14-19-12.png we can see Display true as result.

if-else block
to use else block we simple adds an else block to if

If conditon is true then return A else return B

similarly here also it works same if condition is true then show if block otherwise else

Screenshot from 2021-09-24 14-23-46.png

Here as disp is false then else block is displayed ..hope you get an idea to use if-else

Looping in svelte.

If we need to iterate in HTML part ,for that case svelte provide us each block to iterate over array. syntax

{#each array as variable_to_represent_element_of_array}
     <!-- display or perform action on the element extracted -->
    {/each}

Taking an example and will try to understand

<script>
    let names = [
     "rambo","ram","rajni"
    ];
</script>

<h1>The Famous names </h1>

<ul>
    {#each names as name }
       <p> {name}
   {/each}

</ul>

Screenshot from 2021-09-24 15-05-34.png in the same way we can loop over array of objects ,

We can have index value for each element as

{#each names as name ind} // ind shows index value for that element in the array

also its good to give key to each element of the array if we are updating our array ,it helps in proper indexing of the array elements

{#each names as name }
   <p key ={unique_value}> {name}
</p>
{/each> 
 <!-- something like this-->

Hope you learn something. That's all for this blog , in the next part we will look into events in svelte and how to handle them

Thank you for reading the blog and if you have any suggestions for the next blog please write into comments .