DEV Community

Archit Sharma
Archit Sharma

Posted on

Web Storage in JavaScript

Web Storage, can store data locally within the user's browser.

1) Check Browser Support

Before using web storage, check browser support for localStorage and sessionStorage:

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
} else {
  // Sorry! No Web Storage support..
}
Enter fullscreen mode Exit fullscreen mode

2) To Store Data

Create a localStorage name/value pair with name="fname" and value="Steve"

localStorage.setItem("fname", "Steve");
Enter fullscreen mode Exit fullscreen mode

OR

localStorage.fname = "Steve";
Enter fullscreen mode Exit fullscreen mode

3) To Retrieve Data

Retrieve the value of "fname" and insert it into the element with id="result"

localStorage.getItem("fname");
Enter fullscreen mode Exit fullscreen mode

OR

localStorage.fname;
Enter fullscreen mode Exit fullscreen mode

4) Remove Storage Item

To remove the "fname" localStorage item

localStorage.removeItem("fname");
Enter fullscreen mode Exit fullscreen mode

OR

delete localStorage.fname;
Enter fullscreen mode Exit fullscreen mode

5) Clearing Storage

To Clear (delete) all stored data

localStorage.clear();
Enter fullscreen mode Exit fullscreen mode

6) To Store Structured Data

To store structured data, you can use JSON to serialize it to and from strings for storage

var students = [{name: "Tyler", marks: 22}, {name: "Ryan", marks: 41}];
localStorage.setItem('students', JSON.stringify(students));
console.log(JSON.parse(localStorage.getItem('students')));
// [ Object { name: "Tyler", marks: 22 }, Object { name: "Ryan", marks: 41 } ]
Enter fullscreen mode Exit fullscreen mode

7) Session Storage

The sessionStorage object implements the same Storage interface as localStorage. However, instead of being
shared with all pages from the same origin, sessionStorage data is stored separately for every window/tab.

  • Save data to sessionStorage
sessionStorage.setItem('key', 'value');
Enter fullscreen mode Exit fullscreen mode
  • Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
Enter fullscreen mode Exit fullscreen mode
  • Remove saved data from sessionStorage
sessionStorage.removeItem('key')
Enter fullscreen mode Exit fullscreen mode

8) Error Condition

When browsers are set to prevent cookies, they often block localStorage as well. This will lead to exception if you try to use it. Remember to handle these situations accordingly.

var video = document.querySelector('video')
try {
 video.volume = localStorage.getItem('volume')
} catch (error) {
 alert('If you\'d like your volume saved, turn on cookies')
}
video.play()
Enter fullscreen mode Exit fullscreen mode

If you found this useful, consider:

✅ Follow @iarchitsharma for more content like this
✅ Follow me on Twitter

Top comments (0)