JavaScript Local and Session Storage

Local and session storage is used to store variables and data on disk rather than in memory. Usually when a variable is created in JavaScript the variable will be store in memory, meaning if you keep creating variables then eventually the computer will run out of memory. This is why you may want to store variables on disk, as it can free up memory. Another reason to store variables on disk is to allow the program to exit and still be able to access the variable. Normally when a program is running the variables, and their values, will only exist for as long as the program is running. Storing variables on disk can allow the program the program to exit and the value will still exist, meaning if the program re-starts or re-runs it will be able to access the variable again.

Local storage is one way to store variables on disk in JavaScript. Local Storage is used when you want the variable to persist even after the user exits. This means that is a variable is stored in local storage and then the user closes their browser, or even restarts their computer, when they go back to website the variables and their values would still exist. The below code shows how to use the ‘localStorage’ object in JavaScript to store and retrieve variables. When storing variables using the ‘setItem’ method there are two parameters, the first is the name of the variable and the second is the value. The ‘getItem’ takes one parameter, which is the name of the variable, and will return the value stored in local storage.

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.

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.

Leave a Reply