localStorage

localStorage is a Storage object. Type localStorage in your console and hit enter, you will see a Storage printed.

Console >> localStorage

> Storage { length: 0 }

>>

Expanding the Storage object.

We will see that it inherits from the StoragePrototype that has methods and property:

clear

getItem

key

removeItem

setItem

length

These are the methods localStorage uses to store and retrieve data from its store. localStorage stores data in key/value pairs. Just like in JS plain old object literal and Sets and Maps.

key: “name"

value: “nnamdi"

The key serves as an id to the actual value it stores or holds.

clear: clears the localStorage datastore.

getItem(key): returns the value from the key/value pair based on the key that is sent.

key(index): used to return the key name of a key/value pair from an index.

removeItem(key): this removes a key/value pair from the data store based on the key sent.

setItem(key, value): This will create and set a key/value pair in the localStorage datastore.

length: This is a read-only property. It returns the number of data stored in the localStorage.

localStorage is available in the window object. So it can be called without appending the window. prefix or with the window. prefix:

window.localStorage

localStorage

Some important notes on localStorage

The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).

localStorage.setItem("num", 90)

localStorage.setItem("user", { name: "nnamdi", age: 21 }) localStorage.getItem("num") // "90"

localStorage.getItem("user") // "[ object Object ]"

If we need to save an Object in localStorage, we need to stringify it, that is, use JSON#stringify API to convert the JavaScript value to a JavaScript Object Notation JSON string.

const user = {

name: "nnamdi",

age: 27,

occupation: "doesn't know what he is doing"

} localStorage.setItem("user", JSON.stringify(user))

JSON#stringify will convert the user Object to JSON string "{ name: "nnamdi", age: 27, occupation: "doesn't know what he is doing" }" .

So when we retrieve the user value we get this:

localStorage.getItem("user") // "{ name: "nnamdi", age: 27, occupation: "doesn't know what he is doing" }"

If we hadn’t used JSON#stringify the user Object would be converted to Object string “[object Object]”.

Now, we cannot use the JSON string like that, we cannot access the properties because it is a string. To access the properties we need to convert the JSON string to JavaScript value using the JSON#parse API.

localStorage.getItem("user") // "{ name: "nnamdi", age: 27, occupation: "doesn't know what he is doing" }" const userLocal = JSON.parse(localStorage.getItem("user")) // { name: "nnamdi", age: 27, occupation: "doesn't know what he is doing" } userLocal.name // "nnamdi"

🚩 localStorage operates on a Document’s origin. We only have to be on the same origin (domain/port/protocol), the URL path can be different.

For example, the data stored in localStorage on domain https://doc.origin.com will not be the same on the data stored in localStorage on https://app.inapp.com.

https://doc.origin.com

localStorage.setItem("name", "nnamdi") on https://app.inapp.com

localStorage.setItem("name", "chidume") If we try to get the value of the "name" key: on https://doc.origin.com

localStorage.getItem("name") // "nnamdi" on https://app.inapp.com

localStorage.getItem("name") // "chidume"

🚩localStorage datastore persists even when the browser is shutdown. The data in localStorage will still be available when next the browser is launched.

🚩Data stored in localStorage never expires, that is, it has no limit data or life limit or expiration date. It lives in the browser forever until it is cleared by the user.

🚩Data is never transferred to the server.

🚩Data is shared between all tabs and windows from the same origin.

sessionStorage

The much less used API and brother to localStorage. sessionStorage is an object of the Storage, and also inherits the methods and properties of the Storage parent class, StoragePrototype, just like localStorage does:

clear

getItem

key

removeItem

setItem

length

These APIs do the same thing as we have seen in the localStorage. Just like localStorage, sessionStorage operates on a specific origin(domain/port/protocol).

Example codes:

mySessionStorage = window.sessionStorage || sessionStorage



sessionStorage.setItem("userId", "23ert5Y")

sessionStorage.setItem("name", "nnamdi")



sessionStorage.getItem("userId") // "23ert5Y"

sessionStorage.getItem("name") // "nnamdi"



sessionStorage.length // 2

sessionStorage.key(0) // "23ert5Y"

sessionStorage.key(1) // "nnamdi"



sessionStorage.removeItem("name")

sessionStorage.getItem("name") // undefined



sessionStorage.clear()

sessionStorage.getItem("userId") // undefined

sessionStorage.getItem("name") // undefined sessionStorage.clear()

sessionStorage.getItem("userId") // undefined

sessionStorage.getItem("name") // undefined

Some important notes on sessionStorage

🚩Data stored in sessionStorage have an expiration time. this means that sessionStorage data is cleared when the page session ends.

A page session is held during the lifetime of a tab. The page session ends when:

the tab is closed

the browser/browser window is closed

opening a new tab will create another sessionStorage object even if the tab is of the same origin(domain/port/protocol)

The page session is maintained when:

the tab is refreshed

with iframes.

We create a sessionStorage at https://doc.origin.com



sessionStorage.setItem("name", "nnamdi")



If we open another tab at https://doc.origin.com



sessionStorage.getItem("nnamdi") // undefined



The sessionStorage at the second tab is different from the sessionStorage at the first tab despite being at the same origin https://doc.origin.com, very unlike localStorage.

So it is safe to say that localStorage is shared between tabs on the same origin while sessionStorage is not shared.

🚩The storage limit is larger than a cookie (at most 5MB).

Web Storage event

This is an event registered on the Web storage medium localStorage and sessionStorage , this event is fired when the data in these two are added, cleared or deleted.

To register an event, we do this:

window.onstorage = function(event) {}



window.onstorage = function({

key,

oldValue,

newValue,

url,

storageArea

}) {}

The event param has properties:

key – the key that was changed ( null if .clear() is called).

oldValue – the old value ( null if the key is newly added).

newValue – the new value ( null if the key is removed).

url – the URL of the document where the update happened.

storageArea – either localStorage or sessionStorage object where the update happened

(Info got from https://javascript.info)

Conclusion

Differs

localStorage: shared between tabs

sessionStorage: not shared between tabs.

localStorage: persists and lives when the browser is closed and reopened.

sessionStorage: doesn’t persist, everything is cleared once the browser is closed

localStorage: Has no expiration date

sessionStorage: Expires when the page session ends

Sameness

Holds data on the same origin(domain/port/protocol), the URL path can be different.

The data is stored in String format. Objects, numbers, etc will be converted to a string.

That’s it.

If you have any questions regarding this or anything I should add, correct or remove, feel free to comment, email or DM me.

Thanks!!!

Learn More