Slater New
« back to Blog

Javascript 101: Localstorage

Jared Malan
Director Of Technology
 @
Edgar Allan

Do you use localstorage? It's a tool that we find ourselves turning to more and more as we work on complex Webflow builds. For example, we used localstorage a lot on ask.edgarallan.com.

Localstorage is simple to leverage. Let's hit the key concepts:

What is localStorage? localStorage is a web storage object that allows you to store data in the browser. Unlike sessionStorage, which is cleared when the session ends (e.g., when the browser is closed), localStorage persists even after the browser is closed.

Basic Methods:

  • localStorage.setItem(key, value): Saves data under a specific key.
  • localStorage.getItem(key): Retrieves the value of a specific key.
  • localStorage.removeItem(key): Removes a specific key-value pair.
  • localStorage.clear(): Clears all data stored in localStorage.

Examples:

1. Storing Data
You can store a string as a value in localStorage:

// Store a string
localStorage.setItem('username', 'JohnDoe');

2. Retrieving Data
To retrieve the stored data:

// Get the stored item
const username = localStorage.getItem('username');
console.log(username);  // Output: 'JohnDoe'

3. Removing Data
You can remove a specific key-value pair:

// Remove 'username' from localStorage
localStorage.removeItem('username');

4. Clearing All Data
If you want to clear all stored data:

// Clear everything in localStorage
localStorage.clear();

To finish, let's show a solution to storing and using a user's theme performance:

// Save the theme preference
localStorage.setItem('theme', 'dark');

// Retrieve and apply the theme
const theme = localStorage.getItem('theme');
if (theme) {
 document.body.classList.add(theme);
}

Do you have any localstorage solutions that you want to share? The Community Library has some localstorage scripts that you may find helpful.

Try it out for yourself

Sign up for a free trial and see if Slater is for you.

Share this post

We are building a first-class development experience that bridges together code and no-code.