The main difference between localStorage and sessionStorage is that the localStorage stores data with no expiration date, while the sessionStorage stores data from one session.
Key Areas Covered
1. What is localStorage
2. What is sessionStorage
3. Difference Between localStorage and sessionStorage
-Comparison of key differences
HTML5, localStorage, sessionStorage, Web Storage
What is localStorage
The localStorage is an object that helps to store data with no expiration date. Therefore, this data will not be deleted even the browser is closed. In other words, the user can access a page’s local storage without any time limit. So, it is possible to obtain data the next day or after a week or a year.
Refer to the below code.
document.getElementById(“result1”).innerHTML = localStorage.getItem(“firstname”);
The above code creates a local storage with name and value pair. The name is “firstname” while the value is “Ann”. The second line helps to obtain the value of the firstname and insert it into the element with the id called result1.
Furthermore, it is possible to remove the “firstname” localStorage item as follows.
What is sessionStorage
The functionality of the sessionStorage is similar to localStorage, but it stores data only for one session. Therefore, the data is deleted when the user closes the browser tab. So, it helps to add data to the session storage. It is possible to access it by any page from the same site opened in that window. Once the user closes the window, the session is lost. Likewise, the sessionStorage object allows string data of a specific session.
Difference Between localStorage and sessionStorage
localStorage is a type of web storage object available in HTML 5 that allows storing data with no expiration date. In contrast, sessionStorage is a type of web storage object available in HTML 5 that allows storing data for one session.
Moreover, localStorage is designed for storage that spans multiple windows, and it lasts beyond the current session. On the other hand, sessionStorage allows the user to carry out a single transaction but could be carrying out multiple transactions in different windows at the same time.
In brief, HTML 5 web storage provides two storage objects for storing data on the client machine: localStorage and sessionStorage. They help to store a large amount of data locally than a regular cookie. However, the main difference between localStorage and sessionStorage is that the localStorage stores data with no expiration date, while the sessionStorage stores data from one session.