Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 12, 2021 08:42 pm GMT

Javascript local storage - beginner's guide

Before going into any kind of explanation, we need to understand the difference between server side storage and client side storage when it comes to websites and applications. Server side means that we store our data on a server, using a database, cleint side consists of JavaScript APIs that allow you to store data on the client (in the browser).

WHAT IS LOCAL STORAGE?
In simple terms, the local storage can be compared to a data base, except it's found in a browser and not on a server. It's basically a huge Javascript object inside which we are able to store data in the form of key-value pairs. Not only we can store data, we can also delete or retrieve it (a complete list of browsers which have a localStorage cant be found here). The data you store in the localStorage never leaves you machine (doesn't get sent back to the server, unlike with cookies, which will discuss in a future article), and depending on the browser, you can store up to 5MB of data.

In technical terms,

the localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin;
the stored data is saved across browser sessions.

WHY USE IT?
Local storage lets us cache some application data in the browser, for later usage. Therefore, it is very useful if we want to speed applications up (since the data is stored totally on the client it does not travel between the client and server on each request or response). This way we can allow an user, for example, to continue a game where they left off or serve them relevant content based on their previous visit of our website.

I'm mostly using it when I'm building static websites. Since I dont need any backend language or logic to store data in the browser, my web pages can run independently of any web server.

There are two types of storages, local and session, but for now the only difference you should remember is that the local storage has no expiration date (meaning that the data will stay in there until we remove it manually), whereas the session one gets cleared once we close the browser (session).

I will be using Chrome browser for this article, but generally, accessing the localStorage of any browser is pretty similar. We open the console (F12), navigate to the Application tab and in the menu on the left we'll see Local storage under the Storage tab. Something like this:

Alt Text

If we expand the Local storage dropdown, we'll get to this view:

Alt Text

We have two columns, Key and Value, and usually they're filled with data, which I just removed before taking the screen shot.

The way we can access this storage object and populate the two columns is by making use of some specific methods. Remember, local storage is read-only, meaning we can add, read and delete data from it but we can't modify it (at most, we can overwrite the previous value of a key, by re-adding to the storage, using the same key and the new value we want to store). For access we should use the following syntax:

window.localStorage //or localStorage

If we want to add something, we can do it like this:

localStorage.setItem("key", "value");

To access a value, we write this:

localStorage.getItem("key");

And lastly, we can delete one specific value:

localStorage.removeItem("key");

Or we can clear the whole local storage:

localStorage.clear();

Now, let's try to actually write some code. I will use my console, for simplicity's sake. Let's add an item:

window.localStorage.setItem("city", "Toronto");

Now, local storage looks like this:
Alt Text

One important thing to remember is that the localStorage can store only strings. To store objects, we must first convert them to strings using the JSON. stringify() method. And we convert the strings back into objects, after we retrieve them from the localStorage, using the JSON.parse().

Let's add some more values, using different types of data as keys and values:

window.localStorage.setItem(0, "number");
const person = {name: "Alan", age: 32};JSON.stringify(person); // returns "{\"name\":\"Alan\",\"age\":32}"window.localStorage.setItem("person","{\"name\":\"Alan\",\"age\":32}");

Now the local storage will look like this:

Alt Text

We can add as many key-value pairs as we want as long as the data doesn't exceed 5MB. Now let's retrieve the value of the person key, convert it to an object and print it to the console:

const result = windows.localStorage.getItem("person");console.log(result); // returns {"name":"Alan","age":32}const objectResult = JSON.parse(result);console.log(objectResult);// returns {name: "Alan", age: 32}

Alt Text

Finally, let's delete one item only, followed by clearing the whole localStorage:

windows.localStorage.removeItem("0");

Alt Text

windows.localStorage.clear();

Alt Text

THINGS TO REMEMBER ABOUT THE LOCAL STORAGE

  • it is tab specific, meaning each browser tab we open will have different data in the localStorage
  • some browsers, when used in incognito mode don't allow for setting data in the localStorage
  • it is synchronous, meaning each operation will execute one after the other (this might work for small projects, but it will impact the runtime of the more complex ones)
  • it can only store data string data (this is fine for small projects, but it can be cumbersome to serialize data in complex ones)

SUPER IMPORTANT THING TO REMEMBER
Local storage should under no circumstances be used to store sensitive information (e.g. passwords or personal details), since the data inside it can be accessed from anywhere on the page (it has no real protection and it's susceptible to cross-site scripting).

Image source: ThisIsEngineering/ @thisisengineering on Pexels


Original Link: https://dev.to/arikaturika/javascript-local-storage-beginner-s-guide-1gk1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To