Session Storage is a web storage object which stores data for one session. The data is deleted when the user closes the specific browser tab. It's a part of the Web Storage API, and allows you to store data on a user's web browser similar to cookies, but it's faster and much easier to work with.
In this tutorial, you will learn how to manage data that only needs to be stored temporarily. You'll learn how to use Session Storage to store, retrieve, and delete data.
To follow along with this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript.
Session Storage stores data as a key-value pair, and it can only store strings. To store objects, you will need to convert them to strings using JSON.stringify. Similarly, to retrieve objects, you will need to parse the string back into an object using JSON.parse.
// Store data
sessionStorage.setItem('name', 'John');
// Retrieve data
let name = sessionStorage.getItem('name');
console.log(name); // Outputs: John
In the above code:
- setItem
method is used to store data. It accepts two parameters - key and value.
- getItem
method is used to retrieve data. It accepts one parameter - key.
- console.log
is used to print the output to the console.
// Store object
let user = {name: 'John', age: 30};
sessionStorage.setItem('user', JSON.stringify(user));
// Retrieve object
let retrievedUser = JSON.parse(sessionStorage.getItem('user'));
console.log(retrievedUser); // Outputs: {name: 'John', age: 30}
In the above code:
- JSON.stringify
is used to convert the object into a string before storing.
- JSON.parse
is used to parse the string back into an object.
// Remove specific data
sessionStorage.removeItem('name');
// Clear all data
sessionStorage.clear();
In the above code:
- removeItem
method is used to remove data. It accepts one parameter - key.
- clear
method is used to clear all data from session storage.
In this tutorial, we covered what session storage is, and how to store, retrieve, and delete data from it. As next steps, you might want to explore the other part of the Web Storage API - Local Storage, which is similar to Session Storage but persists even when the browser is closed.
Store your favorite movie and its release year in session storage. Retrieve and print it to the console.
Store an array of your favorite books in session storage. Retrieve and print them to the console.
Store a list of your favorite songs with their artists in session storage as an object. Retrieve and print them to the console.
Solutions and explanations for these exercises can be found online, but it's recommended to try solving them on your own first. Happy coding!