Skip to content
  • Homepage
  • HTML
  • CSS
  • Symfony
  • PHP
  • How to
  • Contact
  • Donate

Teach Developer

Articles, Guides & Tips

How to use the Local Storage in Javascript

Home  »  JavaScript • Jquery   »   How to use the Local Storage in Javascript
Posted on July 26, 2022July 26, 2022 No Comments on How to use the Local Storage in Javascript
531

This article discusses what local storage is and the JavaScript methods that we can use to manipulate it.

What is Local Storage?

Local storage is a web storage object that is available in a user’s browser. It allows JavaScript browsers to store and access data right in the browser. Basic CRUD operations (create, read, update and delete) can be done on data in the local storage. Data stored in the local storage persists even when the browser window has been closed.

Another form of web storage is Session Storage. This is similar to local storage. The difference is that the data stored in the session storage gets cleared after the session ends, ie. the browser window is closed.

Local Storage Methods

Local Storage methods are the methods that help you manipulate the local storage. That is to save and access data stored in the local storage. These methods include:

  1. setItem()
  2. getItem()
  3. removeItem()
  4. clear()

Let us discuss each of them.

setItem()

We use this method to add new data items to the local storage object or update existing values if the data exists. It takes two arguments, the key of the item to create or update and the value to store. For example, if we want to store a name in the local storage, here is what we will do

    localStorage.setItem('name', 'teachDeveloper');

In the example above, name is the key and teachDeveloper is the value.

This is a simple example. What if you want to store something a little more complex like an array or an object in the local storage? For example, store the notes of the note app in the local storage. It is important to note that local storage stores values as strings. We need to convert the arrays or objects to strings before passing them to the local storage.

We can use the JSON.stringify() method to convert an object or array to strings before passing it to the setItem() method.

    const notes = [
        {  
            title: 'A note',
            text: 'First Note'
        },
        {
            title: 'Another note',
            text: 'Second Note'
        }
    ]

    localStorage.setItem('notes', JSON.stringify(notes))

getItem()

This method is used to access data stored in the local storage. It accepts one argument: the key of the item you want to get the value of. It returns the value as a string.

Let us get the name we stored in the local storage.

    const name = localStorage.getItem('name');
    console.log(name) // 'teachDeveloper'

What if we want to get the notes we stored in the local storage. we do the same thing, pass the key to the getItem method. However, to get our value as an array, we need to parse it. Otherwise, it returns strings.

    JSON.parse(localStorage.getItem('notes'))

removeItem()

The removeItem() method removes data from the local storage. It receives a key and removes the data item stored with that key from the local storage. If that key does not exist in the local storage, it does nothing.

    localStorage.removeItem('name')

    console.log(localStorage.getItem('name')) //null

clear()

The clear() method clears the entire local storage of all data stored in it. It does not receive any argument.

    localStorage.clear()

Those are the methods available to store and retrieve data from the local storage. Next, let us see how we can listen to storage change events.

Event Listener for Storage Change

To listen to changes in the local storage, we add an event listener for storage.

    // When local storage changes, execute the doSomething function
    window.addEventListener('storage', doSomething())

The storage event fires when either the local storage or the session has been modified in the context of another document. This means that the storage event is not fired on the page that is making changes to the local storage. Rather it is fired in another tab or window if the same page is open there. The assumption is that your page already knows all changes that happen on it. That it will only need notification if the change happens on another page.

I encountered this challenge when building the note app. I was trying to update the part that displays the notes based on changes in the local storage. However, I noticed that when I add a new note, it does not update the notes. Rather it updates the same page opened in another tab. To solve this, I used a state object. After storing to the local storage, I stored or updated a new note in this state. The display of the notes depends on the changes to the state.

Important Things to Note about the Local Storage

One last thing before we go, there are important things about the local storage that we should know.

  1. The local storage is limited to 5MB across all major browsers.
  2. It can easily be accessed from the browser so it should not be used to store any sensitive data or user information.
  3. Operations on the local storage are synchronous. Therefore, they are executed one after another.
JavaScript, Jquery Tags:Javascript

Post navigation

Previous Post: 4 Methods to Search an Array
Next Post: ES6 classes

Related Posts

  • Best JavaScript Minifying Tools
  • How to Create Live Search in HTML table with jQuery
  • How to use setTimeout and setInterval methods in JavaScript
  • Important most things you should know about JSX
  • Destructuring Assignment in ES6- Arrays
  • How to Object Destructuring in ES6

Leave a Reply Cancel reply

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

Categories

  • Codeigniter (3)
  • CSS (11)
  • eCommerce (1)
  • Framework (1)
  • Git (3)
  • How to (43)
  • HTML (5)
  • JavaScript (15)
  • Jquery (7)
  • Laravel (1)
  • Linux (4)
  • Magento-2 (1)
  • Node js (4)
  • Others (2)
  • PHP (11)
  • React (13)
  • Server (1)
  • SSH (3)
  • Symfony (6)
  • Tips (16)
  • Top Tutorials (10)
  • Ubuntu (3)
  • Vue (1)
  • Wordpress (7)

Latest Posts

  • What is SSH in Linux?
  • How to Delete Files in Ubuntu Command Line
  • How to Deploy a React application on a cPanel
  • How to use events listeners and Event Subscriber in Symfony
  • How to Convert PHP CSV to JSON

WEEKLY TAGS

AJAX (1) Codeigniter (1) Javascript (11) JQuery (1) PHP (16) Programming (1) React (3) Symfony (1)

Random Post

Here are 10 platforms where you can find your next remote job as a developer.
How to Change SSH Port in Linux
How to remove index.php from URL in CodeIgniter 4
How to split a string into an array with Twig
How to check if a customer is logged in to Magento 2 or not?

Quick Navigation

  • About
  • Contact
  • Privacy Policy

© Teach Developer 2021. All rights reserved