How to Save High Scores in Local Storage

Michael Karén
4 min readJan 11, 2021
Photo by Senad Palic on Unsplash

After creating a game, it would be nice to save our best scores. If we only save the score in memory it will be gone the next time we play. Instead, we can save the scores in the browser’s local storage.

This article steps through how to save high scores in local storage and then how to present them on the screen for the player. If you want to read about the games that inspired this article you can read about it here:

Local storage

With local storage, we can store data in the browser in the form of key-value pairs, where both the key and the value are strings. The data is persisted across browser sessions and its scope is limited to the origin where the script that accesses local storage resides.

Different browsers use different storages, so data is not shared between different browsers on the same computer — each browser has its unique storage.

The following snippets show how we can use localStorage:

With this knowledge, we can start implementing our solution.

Load high scores

Let’s start by defining a couple of constants:

const NO_OF_HIGH_SCORES = 10;
const HIGH_SCORES = 'highScores';

Since we want to store an array we need to translate the array into a string before we save it and back to an array when getting it. For this, we can use the JSON object that contains methods for parsing JSON and converting values to JSON.

We can parse the string that we get from localStorage. If we don’t have any scores saved yet we can use the nullish coalescing operator (??) to give a default value of empty array:

const highScoreString = localStorage.getItem(HIGH_SCORES);
const highScores = JSON.parse(highScoreString) ?? [];

The nullish coalescing operator

--

--

Michael Karén

Frontend Architect • JavaScript Enthusiast • Educative.io Author • ngVikings organizer.