Web Storage Methods: setItem(), getItem(), removeItem(), clear()
The localStorage and sessionStorage objects provide a simple, consistent API for interacting with the browser's key-value storage. Mastering these four core methods is essential for managing data client-side.
Remember, both localStorage and sessionStorage strictly store data as strings. When you need to store numbers, booleans, objects, or arrays, you'll use JSON.stringify() to convert them to strings before saving and JSON.parse() to convert them back when retrieving.
1. setItem(key, value)
The setItem() method is used to add a new key-value pair to the storage or to update the value of an existing key.
key: A string representing the name of the key you want to create or update.value: The data you want to store. This value will always be converted to a string before being stored.
// --- Basic Usage ---
localStorage.setItem('username', 'Alice');
sessionStorage.setItem('currentStep', '3');
// --- Storing Numbers (they are implicitly converted to strings) ---
localStorage.setItem('userAge', 30); // Stored as "30"
// --- Storing Booleans (they are implicitly converted to strings) ---
localStorage.setItem('isLoggedIn', true); // Stored as "true"
// --- Storing Objects/Arrays (MUST use JSON.stringify()) ---
const userPreferences = { theme: 'dark', notifications: true };
localStorage.setItem('preferences', JSON.stringify(userPreferences));
const shoppingCart = ['apple', 'banana', 'orange'];
sessionStorage.setItem('cartItems', JSON.stringify(shoppingCart));
console.log('setItem() examples executed.');
2. getItem(key)
The getItem() method retrieves the value associated with a specified key from the storage.
key: A string representing the name of the key whose value you want to retrieve.- Returns: The value as a string if the key exists, or
nullif the key is not found in the storage.
// --- Basic Usage ---
const username = localStorage.getItem('username'); // "Alice"
const currentStep = sessionStorage.getItem('currentStep'); // "3"
const nonExistent = localStorage.getItem('nonExistentKey'); // null
console.log('Retrieved username: ' + username);
console.log('Retrieved currentStep: ' + currentStep);
console.log('Retrieved nonExistentKey: ' + nonExistent);
// --- Retrieving Numbers/Booleans (they come back as strings) ---
const userAgeString = localStorage.getItem('userAge'); // "30"
const userAgeNumber = parseInt(userAgeString); // Convert back to number
console.log('Retrieved userAge: ' + userAgeNumber + ' (Type: ' + (typeof userAgeNumber) + ')');
const isLoggedInString = localStorage.getItem('isLoggedIn'); // "true"
const isLoggedInBoolean = isLoggedInString === 'true'; // Convert back to boolean
console.log('Retrieved isLoggedIn: ' + isLoggedInBoolean + ' (Type: ' + (typeof isLoggedInBoolean) + ')');
// --- Retrieving Objects/Arrays (MUST use JSON.parse()) ---
const preferencesString = localStorage.getItem('preferences'); // '{"theme":"dark","notifications":true}'
const preferencesObject = JSON.parse(preferencesString);
console.log('Retrieved preferences object: ' + JSON.stringify(preferencesObject));
console.log('Preferences theme: ' + preferencesObject.theme);
const cartItemsString = sessionStorage.getItem('cartItems'); // '["apple","banana","orange"]'
const cartItemsArray = JSON.parse(cartItemsString);
console.log('Retrieved cart items array: ' + JSON.stringify(cartItemsArray));
console.log('First cart item: ' + cartItemsArray[0]);
3. removeItem(key)
The removeItem() method deletes a specific key-value pair from the storage.
key: A string representing the name of the key to remove.- Behavior: If the specified key does not exist, the method does nothing and no error is thrown.
// --- Basic Usage ---
localStorage.setItem('tempData', 'some value');
console.log('Before removal (tempData): ' + localStorage.getItem('tempData'));
localStorage.removeItem('tempData');
console.log('After removal (tempData): ' + localStorage.getItem('tempData')); // Should be null
// --- Removing a non-existent key (does nothing) ---
localStorage.removeItem('definitelyNotThere');
console.log('Attempted to remove a non-existent key. No error occurred.');
4. clear()
The clear() method removes all key-value pairs from the entire storage (either localStorage or sessionStorage). Use this method with caution, as it will wipe out all data for the current origin in that specific storage type.
// --- Basic Usage ---
localStorage.setItem('setting1', 'value1');
localStorage.setItem('setting2', 'value2');
sessionStorage.setItem('temp1', 'val1');
console.log('localStorage items before clear: ' + localStorage.length); // 2
console.log('sessionStorage items before clear: ' + sessionStorage.length); // 1
localStorage.clear();
console.log('localStorage cleared. Items after clear: ' + localStorage.length); // 0
// sessionStorage remains unaffected
console.log('sessionStorage items after localStorage.clear(): ' + sessionStorage.length); // 1
sessionStorage.clear();
console.log('sessionStorage cleared. Items after clear: ' + sessionStorage.length); // 0
5. Comprehensive Example: Managing User Preferences
This example combines all four methods to simulate managing user preferences in localStorage.
Exercise: A Simple Task List in localStorage
Instructions:
You will create a basic task list manager using localStorage.
- Add Tasks: Create a function
addTask(taskText)that:- Retrieves the current list of tasks from
localStorage(or initializes an empty array if none exist). Remember to parse it from JSON. - Adds the new
taskTextto the array. - Saves the updated array back to
localStorage(remember to stringify it) under the key"myTasks".
- Retrieves the current list of tasks from
- Display Tasks: Create a function
displayTasks()that:- Retrieves the
myTasksarray fromlocalStorage. - Logs each task to the console, prefixed with its index (e.g., "1. Buy groceries").
- Logs a message if no tasks are present.
- Retrieves the
- Remove Task: Create a function
removeTask(index)that:- Retrieves the
myTasksarray. - Removes the task at the specified
index(adjust for 0-based array index). - Saves the modified array back to
localStorage. - Handles invalid indices gracefully (e.g., "Task not found").
- Retrieves the
- Clear All Tasks: Create a function
clearAllTasks()that useslocalStorage.clear()(orlocalStorage.removeItem('myTasks')if you want to be specific to just this exercise's data).
Execution Flow in the Editor:
- Call
addTaska few times. - Call
displayTasks. - Call
removeTaskfor one of the items. - Call
displayTasksagain to show changes. - Call
clearAllTasks. - Call
displayTasksone last time to confirm empty.

