Skip to Content
Course content

88: Web Storage: localStorage and sessionStorage

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're working at a desk. On your monitor, you have a few sticky notes with temporary reminders—maybe a phone number for a call you need to make in ten minutes. Once you finish your shift and leave the office, those sticky notes get tossed in the trash. But, you also have a desk drawer where you keep a notebook. Anything you write in that notebook stays there, even after you go home for the weekend and come back on Monday morning.

In the browser, sessionStorage is your sticky note. It's great for data that only needs to last as long as the tab is open. If the user closes the tab or the browser, that data vanishes. localStorage is your desk drawer. It persists. If the user closes the browser, restarts their computer, or comes back a month later, that data is still sitting there waiting for them.

The difference between a quick note and a permanent record

Both of these tools use a "key-value" system. Think of it like a label on a folder. You don't just throw data into the void; you give it a name so you can find it later. Here is how they look in action:

// This survives a browser restart
localStorage.setItem('username', 'DevNinja99');

// This disappears when the tab is closed
sessionStorage.setItem('currentStep', '2');

To get that data back, you just ask for it by the label you created. If the key doesn't exist, JavaScript won't crash; it'll just hand you back null. I've spent way too many hours debugging "undefined" errors because I forgot to check if a value actually existed in storage before using it. Always verify your data first.

const user = localStorage.getItem('username');
if (user) {
    console.log(`Welcome back, ${user}!`);
}

The "String Only" Trap

Here is the part that trips up almost everyone when they first start with Web Storage: it only stores strings.

If you try to save a JavaScript object or an array directly, the browser will try to be "helpful" and convert it to a string. You'll end up saving the literal text "[object Object]", which is completely useless when you try to retrieve it. To get around this, we use JSON. I use this pattern in almost every project I build.

const settings = { theme: 'dark', notifications: true };

// WRONG: This saves "[object Object]"
localStorage.setItem('userSettings', settings);

// RIGHT: Convert the object to a JSON string first
localStorage.setItem('userSettings', JSON.stringify(settings));

// To get it back, parse it back into an object
const savedSettings = JSON.parse(localStorage.getItem('userSettings'));
console.log(savedSettings.theme); // 'dark'

Cleaning up the clutter

You can't let storage grow forever, or you'll eventually hit the browser's limit (usually around 5MB, which sounds like a lot until you start storing large datasets). You have two ways to clean up. You can target a specific "folder" to delete, or you can just clear the whole drawer.

// Remove just the username
localStorage.removeItem('username');

// Wipe everything in localStorage for this domain
localStorage.clear();



📋 Practical Task

Build a Persistent User Preference Toggle

Your goal is to create a small feature that remembers a user's preference for "Light Mode" or "Dark Mode" even after the page is refreshed.

Requirements:

  • Create a button in HTML that toggles between "Light" and "Dark".
  • When the button is clicked, update the document body's background color and text color.
  • Save the current choice ('light' or 'dark') to localStorage whenever it changes.
  • Write a script that runs immediately when the page loads to check localStorage. If a preference was previously saved, apply that theme to the page automatically.

Hint: Use a simple if/else statement on page load to check localStorage.getItem('theme') before deciding which CSS styles to apply.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.