DEV Community

Kelvin Sowah
Kelvin Sowah

Posted on

How To Use LocalStorage

javascript banner

Welcome again, reader, to another entry in my blog where I attempt to demystify and explain a technical topic. I'm going to concentrate on localStorage this time.

What is LocalStorage?
In the simplest terms, localStorage is a feature of the browser that enables us to save data inside the browser. With one very significant exception, it functions quite similarly to sessionStorage. Even when you exit the browser window, data stored in localStorage will continue to exist in the browser. The information kept in sessionStorage, on the other hand, will be erased when the user closes the browser window.

What kind of data can be kept in localStorage?
Key-value pairs are used to store data in localStorage. I want to make one very crucial point: localStorage can only be used to store strings. An object from an array will be automatically transformed into a string if you attempt to store it. Use the JSON.parse() method if you want to change the string back to its original data type.

How do we communicate with localStorage?
We can interact with localStorage using a number of inbuilt ways. The capabilities of each of these techniques are listed in detail below.

localStorage.setItem()

Two arguments are expected by this method. Both the first and the second are pieces of information you want to store. Since localStorage may only hold strings, both arguments must be strings. I've provided an example below to assist you understand my perspective.

localStorage.setItem("name", "Kelvin Sowah")
Enter fullscreen mode Exit fullscreen mode

The name key and its value are essentially stored in localStorage by the code above.

localStorage.getItem()

This method's objective is to fetch data from localStorage. The key of the value you wish to obtain from localStorage is the only input this function expects.

localStorage.getItem("name")
Enter fullscreen mode Exit fullscreen mode

The value corresponding to the key of name will be returned by the code example above. It will return "Kelvin Sowah" in our case.

localStorage.removeItem()

The method's name implies that you can use it to delete a single set of key-value pairs from localStorage. One parameter, which might be any of the keys in localStorage, is required by the method.

localStorage.removeItem("name")

Now, there shouldn't be any data with the key name in our localStorage.

localStorage.clear()

In contrast to the previous method, this one completely clears the localStorage.

I appreciate you reading my brief but enlightening blog. Hopefully, you now have a clearer idea of what localStorage is and know how to use it.

Top comments (1)

Collapse
 
codewithkevin profile image
Kevin Black

Nice