JS SessionStorage 🎯

beginner
15 min

JS SessionStorage 🎯

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!

What is SessionStorage? 📝

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.

Setting Data in SessionStorage 📝

To set data in SessionStorage, you can use the setItem method.

javascript
sessionStorage.setItem('key', 'value');

In the example above, 'key' is the name you give to the data, and 'value' is the data itself.

Retrieving Data from SessionStorage 📝

To retrieve data from SessionStorage, you can use the getItem method.

javascript
let value = sessionStorage.getItem('key');

In the example above, 'key' is the name you gave to the data when you set it in SessionStorage.

Removing Data from SessionStorage 📝

To remove data from SessionStorage, you can use the removeItem method.

javascript
sessionStorage.removeItem('key');

In the example above, 'key' is the name you gave to the data when you set it in SessionStorage.

Clearing All Data in SessionStorage 📝

To clear all data from SessionStorage, you can use the clear method.

javascript
sessionStorage.clear();

💡 Pro Tip: Clearing SessionStorage also clears the data for all tabs/windows within the browser.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does SessionStorage store data for?

Practical Application 🎯

Let's create a simple to-do list application using SessionStorage.

javascript
// 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! 💻🎉