logo javascript

Javascript Course for Beginners

Instructor: Ivan Lourenço Gomes

LocalStorage

Local Storage is a property of the window object that can store data in the user's computer. By doing this we can remember information to use everytime this user visits the website.

We could store the user's name, preferences etc. but never sensitive information like passwords or confidential information because localStorage is not a safe place to do it.

Data is stored in localStorage as key value pairs and the value must always be in string format

Storing data

We use the setItem to store data in localStorage:

                    
    window.localStorage.setItem("name", "ivan");
    // As we already learned, the window object can be ommited for simplicity
    
    // Getting data stored in localStorage is as easy as getting values from objects:
    console.log( localStorage['name'] );
    // or
    console.log( localStorage.name );
                    
                
This information is stored indefinitely until the user cleans the localStorage or the data is erased via Javascript code. The user can access all information stored in localStorage by going to the Application tab in the developer tools, under Storage > Local Storage.

Remove data

We use the removeItem method to erase data from the localStorage.

                    
    localStorage.removeItem("name");
                    
                

sessionStorage

sessionStorage is very similar to localStorage with the difference that the data is only kept during the session. This means that if the user closes the tab or the browser, the information is erased.

sessionStorage also uses the setItem and removeItem methods to store and erase data.

A practical example

  

Contents