DEV Community

blazepk
blazepk

Posted on

WebStorage Apis (part 1)

*Web Storage APIs: What are they and how do they work?
*

Web Storage APIs are a set of JavaScript APIs that allow web applications to store and retrieve data locally on a user's browser. This data can be used to provide offline functionality or to improve the performance of a web ``application by caching frequently used resources.

There are two types of Web Storage APIs: localStorage and sessionStorage. Both of these APIs provide a key-value store that can be used to store data on the client-side.

localStorage

localStorage is a persistent storage API, meaning that the data stored using localStorage will persist even after the browser is closed or the computer is restarted. This makes it a good choice for storing data that needs to be accessed across multiple sessions.

To use localStorage, you can simply set a key-value pair using the setItem() method:

localStorage.setItem('myKey', 'myValue');

You can then retrieve the value using the getItem() method:

var myValue = localStorage.getItem('myKey');

localStorage also provides methods to remove items, clear the entire storage, and get the number of items stored:

`
localStorage.removeItem('myKey');
localStorage.clear();
var itemCount = localStorage.length;
`

sessionStorage

sessionStorage is similar to localStorage, but it is a session-based storage API. This means that the data stored using sessionStorage will only persist for the duration of the browser session. Once the browser is closed, the data is lost.

To use sessionStorage, you can set a key-value pair using the setItem() method, just like with localStorage:

sessionStorage.setItem('myKey', 'myValue');

And retrieve the value using the getItem() method:

var myValue = sessionStorage.getItem('myKey');

sessionStorage also provides methods to remove items, clear the entire storage, and get the number of items stored:

`
sessionStorage.removeItem('myKey');
sessionStorage.clear();
var itemCount = sessionStorage.length;
`

Conclusion

Web Storage APIs provide a convenient way to store and retrieve data locally on a user's browser. By using these APIs, web applications can provide offline functionality and improve performance by caching frequently used resources. The localStorage API provides persistent storage that lasts across multiple sessions, while the sessionStorage API provides session-based storage that lasts for the duration of a browser session.

Top comments (0)