JavaScript localStorage: The complete guide

javascript-localstorage:-the-complete-guide

Introduction

JavaScript localStorage is basically storage that is in the browsers Window Object. You can store anything in the localStorage and it will be persistent through page loads and even if the browser closes and reopens

localStorage and its related sessionStorage are part of the Web Storage API. We will be learning more about these below

What is Web Storage API?

Web Storage API provides methods through which browsers can store key/value pairs of data (like Objects).

The key/value pairs stored in the web storage API are always in the form of strings. (integer keys are automatically converted to strings)

There are a set of methods provided by the Web Storage API that you can use to access, delete modify the key/Value pairs

There are two types of storage available in the Web Storage API

  1. sessionStorage

  2. localStorage

What is LocalStorage?

LocalStrorage is part of the Web Storage API. It allows you to store persistent data (data remains on the browser reloads and when the browser is closed and reopened) in the browser Window Object as key/value pairs of strings.

There are five methods of localStorage and these are:

  1. setItem

  2. getItem

  3. removeItem

  4. clear

  5. key

Difference between sessionStorage and localStorage

Both sessionStorage and localStorage are part of the web storage api.

  • The sessionStorage is only available till the browser is open, when the browser is closed the sessionStorage is deleted. (sessionStorage is available when the browser reloads but when the browser is closed sessionStorage is deleted)

  • The localStorage is the persistent data even when the browser is closed the localStorage data remains in the browser

  • localStorage can be deleted manually by the user and it is automatically deleted when the user is in an incognito window or private window and the user closes the browser

Both sessionStorage and localStorage provides similar methods to access and store data in the browser

We will be learning more about the LocalStorage methods below

localStorage Methods

There are five methods in the localStorage. These methods let you store items, get Items, remove Items and clear the localStorage.

1. setItem(): Store data in the localStorage

Using localStorage.setItem API you can store key/value pairs in the local storage. here is an example on how you can store the data.

window.localStorage.setItem('candy name', 'Mars Bar');

the candy name is the key and the Mars Bar is the value. As we have mentioned localStorage only stores strings.

You can try this in the browser itself. Here is an example to storing the data in the chrome browser

Image description

There are multiple ways of storing the data in the localStorage using setItem. You can access data in the Object like way:

window.localStorage.candyName = 'Mars';
window.localStorage['candyName'] = 'Mars';
window.localStorage.setItem('candyName','mars');

It is allowed but not recommended to store or access data in the object-like way because the user-generated key can by anything like toString or length or any other built in method name of the localStorage

In which case the getItem and setItem would work fine but the Object like method would fail

using Object like notation

Image description

2. getItem(): Retrieve data from the localStorage

Using the getItem API we can retrieve the key/value pairs stored in the localStorage

getItem() accepts a key and returns the value as a string

This would return the value as Mars Bar

Image description

using Object Notation

Using Object notation you can also access the data (although it is not recommended)

window.localStorage.candyName
returns 'Mars'
window.localStorage['candy2']
returns 'turtles'

Image description

3. removeItem() Remove an item from the localStorage

you can remove any item from the localStorage using the removeItem method

Pass the key of the item that you need to remove to the removeItem method and it is deleted from the localStorage

window.localStorage.removeItem('candies');

let’s use the console to see how the removeItem works. First, we will use the length property to check how many items are in the local storage

Image description

As you can see when we use the length property it shows there are 2 items in the localStorage. After we remove an item now there is only one item remaining in the local storage

4. clear() clear the localStorage

With Clear() method of the localStorage API you can clear the entire localStorage and delete all the data in the localStorage

window.localStorage.clear();

let us use the console to see how the clear method of the localStorage works

We will use the length to check for the number of items in the localStorage

Image description

5. key() returns the n th key in the storage

the key method can be passed any integer and it will return the key stored at the nth key in the storage Object

window.localstorage.key(index)

Let us use the console to see how the key works

We have put key/value pairs in the localStorage like

window.localStorage.candyName = 'Mars'
window.localStorage['candy2'] = 'turtles'

let us use the length to check for the contents of the localStorage

window.localStorage.length

Image description

as you know the index starts from 0. let us see what is at index 0

Image description

and let us see what is at index 1

Image description

Storage Property

length : number of key/value pairs stored in the local

The length is a read-only property of the localStorage interface. It returns the number of key/value pairs stored in the localStorage

window.localStorage.length

We can use length property to test whether the localStorage is populated or not.

Uptill now we have used the length property multiple times and you might have become familier with.

Let us use the length property in different use cases to futher explore its uses. Let us open the console and see how we can use the length property

window.localStorage.length
2

Image description

now the length property can also be used to check if the localStorage is empty. Let us clear the localStorage and see what happens if we use the length property

Image description

It returns 0. hence we know if the length property returns 0 then the localStorage is empty

Storage Event

The storage event is fired whenever a change is made to the storage Object

StorageEvent is sent to the window when a storage area the window has access to is changed within the context of another document

Storage event are events that are fired whenever a change takes place and you can listen to the storage event and make appropriate decision in your website or application.

Constructor

StorageEvent()

Returns a new StorageEvent Object

let us use the console to create a new instance of the storageEvent()

creating a new instance of the StorageEvent

new window.StorageEvent(keys)

returns

Image description

Instance Properties

Keys (read only)

Returns a String that represents the key that has been changed. The key attribute is null when the change is caused by the clear() method

newValue(read only)

Returns a String with the new value of the key that has been changed. It is null when clear() method has been used or the key has been removed

oldValue(read only)

Returns a String with the original value of the key. It is null when a new key has been added where there was no key before

storageArea(read only)

Returns a storage Object that represents the storage area that was affected.

url(read only)

Returns a string with the url of the document who key is changed

LocalStorage: Interesting facts

Here are some of the interesting facts about the localStorage

  1. localStorage is always stored in UTF-16 string format. Integer keys are converted into string and stored in the localStorage

  2. localStorage data is specific to the protocol of the browser and website. For example, it is different in HTTP and HTTPS

  3. for documents loaded from file the requirements for localstorage is undefined and is different for different browsers

  4. localStorage for incognito or private browsers is deleted when the browser is closed

LocalStorage Limitations

Here are some of the limitations for localStorage

  • Limited upto 5MB of data

  • do not store sensitive data in localStorage as it can be easily accessed by  cross site scripting

  • localStorage is synchronous meaning it is accessed one after the other and

  • do not use localStorage as a database.

Detecting localStorage: testing for availability

Browser Compatibility

LocalStorage is compatible with all the latest browsers. Only the very very old browsers like Internet Explorer 6 or 7 do not support localStorage

In some situations like the user is in private window or the user is in incognito window the data would be immediately deleted when the user closes the window

The user can also disable localStorage

Exceptions

securityError

A security error is thrown in the following cases:

  • Origin is not a valid scheme/host/port tuple error. This happens when the origin uses file: or data: schemes. Many modern browsers treat file: origin as opaque origin. What this means is that the file or files that come from the same folder are assumed to come from different sources and could trigger CORS error

  • The request violates a policy decision. For example, the user has disabled the use of localStorage on the browser

Conclusion

In this article, I have explained the localStorage and its methods and how you can use localStorage to save data and access it, deleted it and modify it

Note: This article was originally written on the DeadSImpleChat Blog: JavaScript localStorage: The Complete Guide

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
project-design-in-project-management:-a-quick-guide

Project Design in Project Management: A Quick Guide

Next Post
build-an-seo-report-in-seconds-with-domain-overview

Build an SEO Report in Seconds with Domain Overview

Related Posts