How to Use localStorage in JavaScript

In this tutorial, you will learn how and when to use localStorage in JavaScript. Learn how to save, retrieve, and delete items in localStorage. And create a to-do app to see how localStorage works in a practical scenario.

It can be quite infuriating when you accidentally close a webpage when filling out a form. You lose all the data already filled and have to start over. In this article, you’ll learn how to use localStorage in JavaScript to save your data beyond a single browsing session. We’ll show you how to use this mechanism and Window.localStorage property and review the basics of web storage in JavaScript.

Contents:

  • What is localStorage in JavaScript?
    • What is Window.localStorage?
    • When to use localStoage
    • Where is localStorage stored?
  • Understanding the Web Storage API
    • What is the difference between sessionStorage and localStorage?
  • Advantages and disadvantages of localStorage
  • How does localStorage work?
    • Storing data with setItem()
    • Retrieving data with getItem()
    • Deleting data with removeItem()
    • How to delete all items in localStorage: clear()
    • How to get the name of a key: key()
  • Storing data in the browser with localStorage
  • localStorage vs. cookies
  • localStorage browser support

What is localStorage in JavaScript?

localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored persists even after the user closes the browser or restarts the computer.

localStorage is a window object property, which makes it a global object that can interact with and manipulate the browser window. It can also be used in combination with other window properties and methods.

What is Window.localStorage?

The localStorage mechanism is available via the Window.localStorage property. Window.localStorage is part of the Window interface in JavaScript, which represents a window containing a DOM document. The Window interface features a wide range of functions, constructors, objects, and namespaces. Window.localStorage is a read-only property that returns a reference to the local storage object used to store data that is only accessible to the origin that created it.

When to use localStorage

While you can store small amounts of data with localStorage, it’s not suitable for large amounts of data. localStorage is accessible to anyone who uses the device, so you shouldn’t use it to store sensitive information. You can use it to store user preferences like the language or theme. You can also use it to cache data if you use it frequently. localStorage can store form data that won’t be lost if the user closes the browser.

If you have an application that requires you to log in, localStorage can be used to keep your session data. You can remain logged in even after closing and reopening the browser. So, basically, localStoage is used for storing and retrieving data. We’ll demonstrate this later in this tutorial using a simple to-do app.

Where is localStorage stored?

In Google Chrome, web storage data is saved in an SQLite file in a subfolder in the user’s profile. The subfolder is located at \AppData\Local\Google\Chrome\User Data\Default\Local Storage on Windows machines and ~/Library/Application Support/Google/Chrome/Default/Local Storage on macOS. Firefox saves storage objects in an SQLite file called webappsstore.sqlite, which is also located in the user’s profile folder.

Understanding the Web Storage API

localStorage is one of two mechanisms for the Web Storage API, the other being sessionStorage. The Web Storage API is a set of mechanisms that enable browsers to store key-value pairs. It is designed to be much more intuitive than using cookies.

The key-value pairs represent storage objects, which are similar to objects, except they remain intact during page loads and are always strings. You can access these values like an object or using the getItem() method (more on that later).

What is the difference between sessionStorage and localStorage?

Both sessionStorage and localStorage maintain a separate storage area for each available origin for the duration of the page session. The main difference between them is that sessionStorage only maintains a storage area. At the same time, the browser is open (including when the page reloads or restores) while localStorage continues to store data after the browser is closed.

Basically, localStorage stores data that won’t expire, while sessionStorage stores data for a single session only. It’s important to note that localStorage data loaded in an incognito browsing session will be cleared once the last private tab is closed.

Advantages and disadvantages of localStorage

localStorage in JavaScript is an important tool for storing client-side data. However, it has several advantages and disadvantages you should consider.

Advantages

The first advantage of localStorage is one we’ve mentioned a few times already, and that’s data stored doesn’t expire. You can still access the data offline, and localStorage caches data that can be used without an internet connection.

Storing data with localStorage is more secure than storing with cookies, and you have more control of your data. Lastly, localStorage has a larger storage capacity compared to cookies. While cookies can only store four kilobytes of data, localStorage can store up to five megabytes of data.

Disadvantages

localStorage is synchronous, meaning each called operation only executes one after the other. This disadvantage depends on the size of the data you are dealing with. While it won’t be a problem if you’re dealing with small amounts of data, it will be as that grows.

Although localStorage is more secure than cookies, you still shouldn’t use it to store sensitive data. Anyone with access to the user’s device can access the data stored with localStorage. Additionally, localStorage can only store strings, so if you want to store other data types, you’ll have to convert them to strings. And finally, storing too much data with localStorage can slow down your application.

How does localStorage work?

You’ve heard it repeatedly by now — localStorage stores data. And, if you’re storing data, it means you may need to retrieve it later. In this section, we’ll go further than these simple definitions and explore exactly how localStorage works — we’re looking under the hood. Here’s a rundown of how it works:

  • setItem(): Add key and value to localStorage
  • getItem(): This is how you get items from localStorage
  • removeItem(): Remove an item from localStorage
  • clear(): Clear all data from localStorage
  • key(): Passed a number to retrieve the key of a localStorage

Storing data with setItem()

The setItem() method allows you to store values in localStorage. It takes two parameters: a key and a value. The key can be referenced later to fetch the value attached to it. Here’s how it should look:

localStorage.setItem('name', 'Obaseki Nosa');

In the code above, you can see that the name is the key and Obaseki Nosa is the value. As we’ve already noted, localStorage can only store strings. To store arrays or objects, you would have to convert them to strings.

To do this, we use the JSON.stringify() method before passing to setItem(), like so:

const userArray = ["Obaseki",25]
localStorage.setItem('user', JSON.stringify(userArray));

Retrieving data with getItem()

getItem() allows you to access the data stored in the browser’s localStorage object. This method accepts only one parameter, which is the key, and returns the value as a string.

localStorage.getItem('name');

This returns a string with a value of "Obaseki Nosa". If the specified key doesn’t exist in localStorage, it’ll return null. In the case of the array, we make use of the JSON.parse() method, which converts a JSON string into a JavaScript object.

JSON.parse(localStorage.getItem('user'));

Using the array we created above, here’s how to retrieve it from localStorage:

const userData = JSON.parse(localStorage.getItem('user'));
console.log(userData);

This method will return the array [ "Obaseki", 25 ]. You can inspect the webpage, and find it in the console, like this:

LocalStorage Array in JavaScript

This screenshot is from Firefox, so it’ll look a little different on other browsers. Let’s compare it with another array that’s not stored with localStorage:

const userArray2 = ["Oscar", 27];
console.log(userArray2);

So now, we have two arrays on the console, as shown below:

LocalStorage in JavaScript Console

Normally, if you comment them out in your code editor, they should disappear from the console. But, anything stored with localStorage will remain. Here’s an example:

LocalStorage in JavaScript Console Example

Deleting data with removeItem()

To delete an item from localStorage, you’ll use the removeItem() method. When passing a key name, the removeItem() method removes the existing key from the storage. If no item is associated with the given key, this method will do nothing. Here’s the code:

.localStorage.removeItem('name');

How to delete all items in localStorage: clear()

To delete all items in localStorage, you will use the clear() method. This method, when invoked, clears the entire storage of all records for that domain. It does not receive any parameters. Use the following code:

localStorage.clear();

How to get the name of a key: key()

The key() method comes in handy when you need to loop through keys but still be able to pass a number or index to localStorage to retrieve the name of the key. Here’s what that looks like:

localStorage.key(index);

The index parameter represents the zero-based index of the key you want to retrieve the name for.

Storing data in the browser with localStorage

We’ve reviewed all the localStorage methods; now we’ll look at them more practically. Here’s a to-do app built with localStorage:

The app has a very simple HTML markup:

<div class="container">
   <div class="to-do-app">
      <h2>To-do App</h2>
      <input type="text" id="item" placeholder="Enter item...">
      <br>
      <br>
      <button onclick="add()">Add Item <i class="fa-solid fa-plus"></i></button>
      <button onclick="del()">Clear all <i class="fa-solid fa-ban"></i></button>
   </div>
   <ul class="to-do-list"></ul><!--to-do items go here-->
</div>

In the code above, we’ve added two click functions, add() and del() that we’ll use later in the JavaScript. The CSS is also simple; you can style it however you like. The important part is the JavaScript. You’ll start by selecting the list where the tasks will be added and the input field, as shown below:

const ul = document.querySelector('ul');
const input = document.getElementById('item');

Next, you load any pre-existing items in localStorage. And, if there aren’t any, you create an empty array, as shown below:

let itemsArray = localStorage.getItem('items') ?
JSON.parse(localStorage.getItem('items')) : [];

Now, we’ll create a function that adds a task, which would be a li, into the empty ul:

itemsArray.forEach(addTask);
function addTask(text){
  const li = document.createElement('li')
  li.textContent = text;
  ul.appendChild(li);
}

Now, we add functionality to the buttons. The Add Item button stores the items in localStorage, and the Clear All button deletes every item. Here’s the code:

function add(){
  itemsArray.push(input.value);
  localStorage.setItem('items', JSON.stringify(itemsArray));
  addTask(input.value);
  input.value = '';
}
function del(){
  localStorage.clear();
  ul.innerHTML = '';
  itemsArray = [];
}

The add() function gets the items from the input field, input.value. It then adds it to the itemsArray and saves it to localStorage while simultaneously adding it to the list. The del() function clears all items from localStorage, removes them from the list, and resets the itemsArray.

localStorage vs. cookies

Both localStorage and cookies are used to store client-side data. As we mentioned before, cookies can only store a maximum of four kilobytes of data, which is significantly less than the five megabytes storage capacity of localStorage.

Cookies are automatically sent to the server with every HTTP request, but localStorage stays local within the user’s device. This can improve web performance and doesn’t increase network traffic because it doesn’t share data with the server.

As we’ve seen, the data you store with localStorage doesn’t expire; it stays indefinitely until you delete it manually. On the other hand, cookies can be set to expire after some time or as soon as you close the browser. Cookies usually store data like user preferences and login/authentication information. This data is accessible across all tabs and windows of the browser. However, localStorage only stores data that are accessible within a specific protocol or domain.

localStorage browser support

localStorage, as a type of web storage, is an HTML5 specification. It is supported by major browsers, including Internet Explorer v8. To be sure the browser supports localStorage, you can check using the following snippet:

if (typeof(Storage) !== "undefined") {
    // Code for localStorage
    } else {
    // No web storage Support.
}

Conclusion

localStorage in JavaScript is a simple and efficient way to store and retrieve data without relying on cookies. In this post, you learned how and when to use localStorage. We covered how to save, retrieve, and delete items in localStorage. We also created a to-do app to see how localStorage works in a practical scenario. Finally, we compared it to cookies.

So, you’ve learned about a great tool that’s easy to use with broad browser support. How will you implement localStorage in your next project? Happy coding!

Source: https://blog.logrocket.com

#javascript

How to Use localStorage in JavaScript
1 Likes1.50 GEEK