Conditionals and looping in svelte
Sveltekit is popular JS framework, we look at some syntax today
What is sveltekit?
Of all the JavaScript frameworks I know svelte has been my favorite for my own personal reasons. I want to talk about this along with vue and htmx in coming days.
We have seen svelte before.
How to setup the project?
npx degit sveltejs/template moz-todo-svelte
cd moz-todo-svelte
npm install
npm run dev
I liked this in favor of the official docs. To learn some tech we must get a minimalist view is my thing. Not too much fluff and complexity.
Why a sea of JS frameworks?
For some reason God knows best the world of JS SPA frameworks has exploded like crazy. There must be at least 20.
But somehow React seems most popular. Several lesser known methodologies exist. Various GUI toolkits like UIKit and many paradigms like card based design, mobile first for SEO and more.
In a frontend centric universe, the end user experience is enhanced by ease of use, responsiveness, speed among other things.
From a progammer’s point of view the weight of the node_modules determines if an SPA tech is worthwhile or not.
What makes svelte special?
Svelte compiles the code first, and does not do runtime checks. That makes things quicker and nicer.
Every JS framework is special in its own way. My point is not to start a war though people normally just stick to what they know.
Looking at conditionals and looping
Svelte has some interesting syntax which is in my humble view more intuitive and easy to memorize. Let us look at if condition and each looping.
{#if !user.loggedIn}
<button on:click={toggle}> Log in </button>
{/if}
Looping with each.
<script>
let fruits = [
{ name: 'Apple' },
{ name: 'Orange' },
{ name: 'Grapes' },
{ name: 'Pineapple' },
{ name: 'Rose apple' },
{ name: 'Passion fruit' }
];
</script>
<h1>The fruits I like</h1>
<ul>
{#each fruits as { name }, i}
<li>
{i}: {name}
</li>
{/each}
</ul>
Code and demo
This is code and demo. main.js
import EachFruit from './EachFruit.svelte';
const app = new EachFruit({
target: document.body,
});
export default app;
Output.
Conclusion
Don’t worry much about sex appeal of output. We are learning a specific syntax in svelte. We can do other amazing demos in coming days. It is important to learn conditionals and looping first. We will see the syntax for elseif and other topics later.
Answer
What is HTMX?
I got this from htmx.org. We have seen this in many newsletters already, and we will continue to look at them. HTMX is only way to get away from SPA and JSON.
Question
How can JSON be replaced?
Feedback
The entire Internet tech landscape is full of SaaS successes of various shapes and colors. You can also be part of this club.
All you need to do is develop a passion for something like JavaScript or Python, then become good at it. Enter flow state by dedication and lots of coding, make a SaaS and market online.