Using Svelte as a Frontend Framework: Building a Higher or Lower Game

It’s an incredibly competitive time for frontend frameworks in the current world of web development, with new frameworks, extensions and features dropping almost daily.

When we think of frontend frameworks we often think of the ‘big three’: React.js, Vue.js and Angular. For years these three frameworks have dominated frontend web development, with each framework offering its own varied range of benefits, drawbacks and features; ultimately giving developers an incredibly in-depth choice (or headache) when it comes to picking the most suitable framework for the tech stack of a given set of project requirements.

The “

However, a new kid on the block is now challenging the ‘big three’: Svelte.

The founders of Svelte describe it as a “radical new approach to building user interfaces”. The key different between Svelte and the big three is that Svelte has no virtual DOM and completes most of its work in an additional compile step that happens when the app is built, rather than completing all this work client side in the browser. Resulting in incredibly fast and easy to build applications.

As a quick tutorial to Svelte and example of how quickly and easily you can create apps using Svelte, we’re going to be creating a higher or lower game, where we generate a hidden random number between 1 and 20, and then submit a guess, which returns ‘higher’, ‘lower’ or ‘correct’. Users have up to 5 guesses, and can reset the game when they’ve either guessed the correct number or ran out of guesses.

We’ll be using Svelte’s online compiler to create the application, so head to https://svelte.dev/repl/hello-world?version=3.16.5 and delete all the placeholder code to begin.

The online Svelte compiler

Creating our UI

Firstly, we’ll need to define a few elements on our userinterface:

  1. The result text, i.e ‘HIGHER’, ‘LOWER’ OR ‘CORRECT’.
  2. An input element to type our guess into.
  3. A button to submit our guess.
  4. Text to show how many guesses we’ve used.
  5. A reset game button for when the game is over so we can play again.
The simple UI we’ll be creating for our Svelte app

So now we know what we’ll need, as Svelte can be used with plain vanilla HTML, CSS and JavaScript we just need to add a set of <script></script> tags to our file and add the following:

<script>    <p>{result}</p>
<input bind:value={guess} type=”number”>
<button on:click={submitGuess}>Submit Guess</button>
<h1>Guesses: {guesses}</h1>

{#if guesses >= 5 || result === ‘CORRECT’}
<button on:click={resetGame}>Reset Game</button>
{/if}
</script>

Taking this apart, I’ll explain a few bits of Svelte syntax that we’ve used here.

We’ve used bind:value={guess} inside our number input element to two-way bind (a common feature of SPA frontend frameworks) a variable called “guess” (that we’ll create later) to this input, so that we can pull in the user’s guess and evaluate it when we hit our submit button.

<input bind:value={guess} type=”number”>

We create a new button element and add a click event to it by adding on:click={submitGuess}, so that when the button is clicked a function is called (that we’ll create later) that evaluates our guess for whether it is higher, lower or correct.

<button on:click={submitGuess}>Submit Guess</button>

We add {guesses} inside our <h1></h1> element to display our bound guesses variables to our actual UI. This is the flip side of the two-way binding we saw earlier in our input element.

<h1>Guesses: {guesses}</h1>

{#if} and {/if} are how we do if statements and conditional rendering in Svelte. We often use this in applications to render, hide or add certain content to our user interface depending on the variables and “state” of our application.

{#if guesses >= 5 || result === ‘CORRECT’}
<button on:click={resetGame}>Reset Game</button>
{/if}

Binding our Variables

Now we’ll need to actually initialise our variables for use in the game, so at the top of file just inside the <script> tag add the following:

let random = getRandNumber();
let result = “-”;
let guess = 0;
let guesses = 0;

Then add the following to create a function that generates and returns a random number between 0 and 20.

function getRandNumber() {
return Math.floor(Math.random() * 11);
}

Linking up our submitGuess() function

Earlier we added a click event for submitting a guess, so we now need to add a function that can evaluate our guess for whether it is higher, lower or correct.

function submitGuess() {
if(guess < random) result = ‘HIGHER’;
if(guess > random) result = ‘LOWER’;
if(guess === random) {
result = ‘CORRECT’;
alert(`CORRECT, NUMBER WAS ${random}. YOU TOOK ${guesses} GUESSES`)
}
guesses++;

if(guesses >= 5) {
result = ‘GAME OVER!’;
alert(`GAME OVER, NUMBER WAS ${random}`)
}
}

At the top of the function we’re just checking how our guess matches up to our random number, and if it’s correct then we alert the user to tell them.

if(guess < random) result = ‘HIGHER’;
if(guess > random) result = ‘LOWER’;
if(guess === random) {
result = ‘CORRECT’;
alert(`CORRECT, NUMBER WAS ${random}. YOU TOOK ${guesses} GUESSES`)
}

We increases our number of guesses by 1.

guesses++;

Then we need to check if we’ve used up all 5 guesses (and the game is over), if so then we change the result and then alert the user that the game is over:

if(guesses >= 5) {
result = ‘GAME OVER!’;
alert(`GAME OVER, NUMBER WAS ${random}`)
}

Now we’ve got our basic game logic sorted and the game is playable for 1 turn. But what we really want is for the user to be able to reset the game and repeatedly play it.

Resetting the Game

Earlier we used an if statement in Svelte to show a reset game button when the game is over, and we added a click event to call a function to reset it:

{#if guesses >= 5 || result === ‘CORRECT’}
<button on:click={resetGame}>Reset Game</button>
{/if}

Now we’ll need to actually create this resetGame() function to reset all our game variables and begin the process again. So we’ll need to add a resetGame() function to our code:

function resetGame() {

}

And then inside the function we just need to reset the variables to their initial state:

function resetGame() {
guesses = 0;
guess = 0;
result = “-”;
random = getRandNumber();
}

This function just resets our variables to their initial state, and gets a new random number, thus beginning the game again!

Our Full Code

Further Development?

Svelte is pretty versatile, and has a relatively small learning curve, so there’s plenty of space for improvements to be made to our game. For example:

  1. We could look into splitting our app up into Svelte components that take props and pass data up and down the component tree as would be seen in a more complex typical single page application.
  2. We could look at more conditional rendering in Svelte and how we could use while loops in our application, for example to show a leaderboard of the best scores.
  3. We could look at other input types and binding these variables across the UI, such as showing the time taken to complete the game, or the current user’s name.
  4. We could look into Svelte’s lifecycle methods, such as onMount(), onDestroy(), beforeUpdate() and afterUpdate() and how we could utilise these to run certain code at key moments in the application’s running, such as getting some leaderboard data during the onMount() lifecycle method.
Comparison between the speed of Svelte and other frontend frameworks.

Conclusion

So now that we’ve seen how quickly we can create an application in Svelte it’s clear to see its benefits over other frontend frameworks such as React, Vue and Angular.

The most notable benefit is how lightweight Svelte is and how easy it is to create simple applications that are powerful, fast and scalable, without needing to bundle potentially unnecessary and redundant large libraries of features and functionality.

Svelte’s use of plain vanilla HTML, CSS and JavaScript make it easy to pickup and learn, meaning that complex applications can be built incredibly quickly whilst simultaneously maintaining the ability to offer the powerful features of a modern frontend framework.

Full Stack Developer at nuom, Nottingham (Joining Experian Consumer Services October 2020) — andrewsmithdeveloper.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store