Welcome to our deep dive into JavaScript's SessionStorage! In this tutorial, we'll explore what SessionStorage is, why we use it, and how to work with it in practical, real-world examples. Let's get started!
SessionStorage is a built-in web storage in your browser that helps you store data with no expiration date for the duration of the session. That means as long as the browser tab is open, the data stored in SessionStorage persists.
💡 Pro Tip: Unlike LocalStorage, which stores data for the entire browser, SessionStorage only stores data for the current tab or window.
To set data in SessionStorage, you can use the setItem method.
sessionStorage.setItem('key', 'value');In the example above, 'key' is the name you give to the data, and 'value' is the data itself.
To retrieve data from SessionStorage, you can use the getItem method.
let value = sessionStorage.getItem('key');In the example above, 'key' is the name you gave to the data when you set it in SessionStorage.
To remove data from SessionStorage, you can use the removeItem method.
sessionStorage.removeItem('key');In the example above, 'key' is the name you gave to the data when you set it in SessionStorage.
To clear all data from SessionStorage, you can use the clear method.
sessionStorage.clear();💡 Pro Tip: Clearing SessionStorage also clears the data for all tabs/windows within the browser.
What does SessionStorage store data for?
Let's create a simple to-do list application using SessionStorage.
// Add a task to the to-do list
function addTask(task) {
let tasks = sessionStorage.getItem('tasks') || [];
tasks.push(task);
sessionStorage.setItem('tasks', tasks);
}
// Get all tasks from the to-do list
function getTasks() {
return sessionStorage.getItem('tasks') || [];
}
// Remove a task from the to-do list
function removeTask(index) {
let tasks = getTasks();
tasks.splice(index, 1);
sessionStorage.setItem('tasks', tasks);
}In this example, we've created three functions: addTask, getTasks, and removeTask. The addTask function adds a task to the to-do list by pushing it to an array stored in SessionStorage. The getTasks function retrieves all tasks from SessionStorage and returns them as an array. The removeTask function removes a task from the to-do list by index, then updates the SessionStorage with the new array.
We hope this tutorial helped you understand and explore JavaScript's SessionStorage. Happy coding! 💻🎉