setItem and getItem
You'll learn how to save and retrieve text data from browser storage using the fundamental setItem() and getItem() methods.
The Core Idea
Think of localStorage or sessionStorage as a simple filing cabinet in the user's browser. The setItem() method lets you file away a piece of information with a label, and getItem() lets you retrieve it later using that same label. Both methods work exclusively with strings — that's their one limitation.
How setItem() Works
To store data, call setItem() with two arguments: a key (the label) and a value (the data):
localStorage.setItem('username', 'AlexDev');
localStorage.setItem('theme', 'dark');
This saves two items: one labeled 'username' with value 'AlexDev', and another labeled 'theme' with value 'dark'. If a key already exists, setItem() overwrites it.
How getItem() Works
To retrieve stored data, call getItem() with the key:
const savedUsername = localStorage.getItem('username');
console.log(savedUsername); // 'AlexDev'
const savedTheme = localStorage.getItem('theme');
console.log(savedTheme); // 'dark'
If you request a key that doesn't exist, getItem() returns null:
const missing = localStorage.getItem('nonexistent');
console.log(missing); // null
sessionStorage Works Identically
You can use the exact same methods with sessionStorage:
sessionStorage.setItem('tempData', 'temporary');
const temp = sessionStorage.getItem('tempData');
The only difference is how long the data lasts — that's determined by which storage object you choose, not by these methods.
Key Takeaway: Use setItem(key, value) to store string data and getItem(key) to retrieve it; these are your fundamental read-and-write operations for browser storage.