JavaScript Learning Local Storage and Session Storage.

 


Before HTML5, application data stored in cookies, included in every server request. But with the Advent of Html5, we have got various options to store information on the client browser. Previously we were having only cookies, which were very restrictive, and the size of the cookies was very small. But now the web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

window.localStorage – It stores the data with no expiration date

window.sessionStorage - It stores the data for one session. That means the data is lost when the browser tab is closed.

LocalStorage: The way to store data on the client's computer is by local storage. The local storage allows us to save the key/value pairs in a web browser, and it stores data with no expiration date. We can access local storage via JavaScript and HTML5. However, the user can clear the browser data to erase all local Storage data.

Both storage objects provide the same methods and properties like setItem, getItem, removeItem, and clear.

// Creating localStorage: localStorage.setItem, Providing key and values (check also console or localStorage)
        let key = 'employees';
        localStorage.setItem(key, 'value');

Reading Entries

let myItem = localStorage.getItem(key);

Updating Entries

localStorage.setItem(key, 'New Value');

Deleting Entries

localStorage.removeItem(key);

Clearing Everything

localStorage.clear();

Storing JSON Objects: Only strings can be stored with localStorage or sessionStorage, but we can use JSON.stringify to store more complex objects and JSON.parse to read them.

    let profile = 'profile';
    let myObj = {name:'Pradeep', profile: 'ui Devloper'};
    // Create
    localStorage.setItem(profile, JSON.stringify(myObj));
    // read
    let item = JSON.parse(localStorage.getItem(profile));
    console.log(item);

Session storage:-The session storage is used to store data only for a session, meaning that it is stored until the browser (or tab) is closed. Remember that, in session storage, the data is never transferred to the server and can only be read on the client-side. The storage limit is between 5-10MB. By opening multiple windows or tabs with the same URL creates sessionStorage for each tab or window.

let impArray = ['adrak', 'pyaz', 'bhindi'];
            sessionStorage.setItem('sessionName', 'Pradeep Bhosle');
            let  seesion1 = sessionStorage.getItem('sessionName');
            console.log(seesion1);
            sessionStorage.setItem('sessionName',JSON.stringify(impArray));

Comments