localStorage.setItem("myKey", "myValue"); localStorage.setItem("myNum", 2); console.log(localStorage.getItem("myKey")); console.log(localStorage.getItem("myNum"));
Variables within local storage can also be deallocated, or deleted, when they are no longer needed. Using the ‘removeItem’ method and passing in the name of the variable will remove the variable from the local storage of the browser. This means you can delete the variables stored on disk when they’re no longer needed.
Session storage works similar to local storage. Using session storage you can set variables, retrieve variables and even remove them, just like when using local storage. The code below shows how to use the ‘sessionStorage’ object to initilise, retrieve, and remove variables. Session storage differs to local storage, as the variables only exist for as long as the session is alive. Unlike local storage, when a user closes the tab or browser then the variables within the session are unallocated and deleted.
sessionStorage.setItem("myKey", "myValue"); sessionStorage.setItem("myNum", 2); console.log(sessionStorage.getItem("myKey")); console.log(sessionStorage.getItem("myNum")); sessionStorage.removeItem("myKey"); sessionStorage.removeItem("myNum");
There is one more method available on both ‘localStorage’ and ‘sessionStorage’. The ‘clear’ method is used to remove all variables that have been allocated, this will effectively delete every variable that is stored within the local or session storage. However, it is worth noting this will only remove variables that your website have set, if a different website has initialised other local or session storage variables then they will not be cleared.