How to Use localStorage in JavaScript: an Easy Guide

The API called Web Storage provides two basic mechanisms for storing information in the user’s browser: sessionStorage and localStorage.

The sessionStorage (which we won’t get into in this article), works very much like the localStorage, but with one difference: it keeps the saved data only until the end of the user session, i.e. until the user’s browser closes, including page reloads or restores.

Photo by Markus Spiske on Unsplash

The localStorage keeps the saved data even if the browser is closed and reopened. This makes it easier to create some interface behavior during user use. And obviously, needless to say, it is not for saving sensitive data.

The data storage structure is quite simple, consisting of the key-value pair. An example:

{
key: value
}

To work with this data, you can do basically 4 actions, using 4 methods:

  • localStorage.setItem() to create a new key-value pair
  • localStorage.getItem() to retrieve the value of a key
  • localStorage.removeItem() to remove a specific pair
  • localStorage.clear() deletes ALL saved pairs for that domain

There is a method called key(). But I won’t talk about it here to simplify the explanations.

Opening localStorage in the browser

To see all the data saved in your browser’s localStorage, simply inspect the page, click on the Application tab, and then, in the sidebar, click on Local Storage (path using Chrome or browsers that use the Chromium engine):

Saving data: localStorage.setItem( )

This method allows you to save the values inside the localStorage in the user’s browser.

Open the console in your browser and execute the following command:

localStorage.setItem("name", "Jack Sparrow");

Now open the Application tab, go to where the localStorages are stored and click on “http://medium.com”. You will see our name: “Jack Sparrow” saved.

Note: Note that the values will always be a string. Therefore, the data that will be saved there needs to be converted to strings before being saved. To do this, simply use the JSON.stringify() method before passing the value to setItem( ).

Now that we saved the value in the user’s browser, we will now retrieve it using the localStorage.getItem() method.

Recovering data: localStorage.getItem( )

Working much like setItem( ), we will use getItem( ) to retrieve the value of a previously saved key. In our case, we will use it to get the name key that we saved in the setItem( ) example.

Execute the following command in your console to see the stored value:

localStorage.getItem("name");

Removing data: localStorage.removeItem( )

After we no longer use this data, it’s a good practice to delete it from the localStorage to avoid unnecessary data accumulation.

The removeItem() method will delete the key you set. If the key doesn’t exist, it will do nothing.

The removeItem() method only removes the key (or object) that you have requested. The localStorage.clear( ) method deletes ALL the keys in your domain. You don’t need to pass any parameters.

Execute the following command in your console to delete a pair and then open the application tab to see if it’s removed:

localStorage.removeItem("name");

Cautions, security and limitations

  • Do not use localStorage to store sensitive data
  • The data that is stored has no layer of access protection, meaning that all data stored there can be accessed by any code on your page
  • In any browser, the localStorage is limited to storing only 5Mb of data.
  • The use of localStorage is synchronous, i.e. every execution is only done one after the other
  • You can only use strings in localStorage, and this sucks, because it limits the storage of more complex data
  • Cannot be used by web workers. This means that if you want to do more complex applications, using background processing to improve performance, you can’t use localStorage because it is not available.

So ideally you should use localStorage for situations where you want to store data that can be public, that is not sensitive, that will not be used in more complex apps, that is no larger than 5MB, and that is strings.

For simple UI things, where it doesn’t make much sense to store something in the database or somewhere more permanent, it is nice to use localStorage.

If you are creating a SPA or any site/system and want a little independence from the server, the use of localStorage is adequate and breaks a lot of steam.

Conclusion

That’s it for today. I hope this article helped you with your web development journey.

Thanks for reading! Follow me in this platform to reed more developer content.

Have a great day, see you soon! 👋

Bit: Build Better UI Component Libraries

Say hey to Bit. It’s the #1 tool for component-driven app development.

With Bit, you can create any part of your app as a “component” that’s composable and reusable. You and your team can share a toolbox of components to build more apps faster and consistently together.

  • Create and compose “app building blocks”: UI elements, full features, pages, applications, serverless, or micro-services. With any JS stack.
  • Easily share, and reuse components as a team.
  • Quickly update components across projects.
  • Make hard things simple: Monorepos, design systems & micro-frontends.

Try Bit open-source and free→

Learn more


How to Use localStorage in JavaScript: an Easy Guide was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.

The API called Web Storage provides two basic mechanisms for storing information in the user’s browser: sessionStorage and localStorage.

The sessionStorage (which we won’t get into in this article), works very much like the localStorage, but with one difference: it keeps the saved data only until the end of the user session, i.e. until the user’s browser closes, including page reloads or restores.

Photo by Markus Spiske on Unsplash

The localStorage keeps the saved data even if the browser is closed and reopened. This makes it easier to create some interface behavior during user use. And obviously, needless to say, it is not for saving sensitive data.

The data storage structure is quite simple, consisting of the key-value pair. An example:

{
key: value
}

To work with this data, you can do basically 4 actions, using 4 methods:

  • localStorage.setItem() to create a new key-value pair
  • localStorage.getItem() to retrieve the value of a key
  • localStorage.removeItem() to remove a specific pair
  • localStorage.clear() deletes ALL saved pairs for that domain

There is a method called key(). But I won’t talk about it here to simplify the explanations.

Opening localStorage in the browser

To see all the data saved in your browser’s localStorage, simply inspect the page, click on the Application tab, and then, in the sidebar, click on Local Storage (path using Chrome or browsers that use the Chromium engine):

Saving data: localStorage.setItem( )

This method allows you to save the values inside the localStorage in the user’s browser.

Open the console in your browser and execute the following command:

localStorage.setItem("name", "Jack Sparrow");

Now open the Application tab, go to where the localStorages are stored and click on “http://medium.com". You will see our name: "Jack Sparrow" saved.

Note: Note that the values will always be a string. Therefore, the data that will be saved there needs to be converted to strings before being saved. To do this, simply use the JSON.stringify() method before passing the value to setItem( ).

Now that we saved the value in the user’s browser, we will now retrieve it using the localStorage.getItem() method.

Recovering data: localStorage.getItem( )

Working much like setItem( ), we will use getItem( ) to retrieve the value of a previously saved key. In our case, we will use it to get the name key that we saved in the setItem( ) example.

Execute the following command in your console to see the stored value:

localStorage.getItem("name");

Removing data: localStorage.removeItem( )

After we no longer use this data, it's a good practice to delete it from the localStorage to avoid unnecessary data accumulation.

The removeItem() method will delete the key you set. If the key doesn’t exist, it will do nothing.

The removeItem() method only removes the key (or object) that you have requested. The localStorage.clear( ) method deletes ALL the keys in your domain. You don’t need to pass any parameters.

Execute the following command in your console to delete a pair and then open the application tab to see if it's removed:

localStorage.removeItem("name");

Cautions, security and limitations

  • Do not use localStorage to store sensitive data
  • The data that is stored has no layer of access protection, meaning that all data stored there can be accessed by any code on your page
  • In any browser, the localStorage is limited to storing only 5Mb of data.
  • The use of localStorage is synchronous, i.e. every execution is only done one after the other
  • You can only use strings in localStorage, and this sucks, because it limits the storage of more complex data
  • Cannot be used by web workers. This means that if you want to do more complex applications, using background processing to improve performance, you can’t use localStorage because it is not available.

So ideally you should use localStorage for situations where you want to store data that can be public, that is not sensitive, that will not be used in more complex apps, that is no larger than 5MB, and that is strings.

For simple UI things, where it doesn’t make much sense to store something in the database or somewhere more permanent, it is nice to use localStorage.

If you are creating a SPA or any site/system and want a little independence from the server, the use of localStorage is adequate and breaks a lot of steam.

Conclusion

That’s it for today. I hope this article helped you with your web development journey.

Thanks for reading! Follow me in this platform to reed more developer content.

Have a great day, see you soon! 👋

Bit: Build Better UI Component Libraries

Say hey to Bit. It’s the #1 tool for component-driven app development.

With Bit, you can create any part of your app as a “component” that’s composable and reusable. You and your team can share a toolbox of components to build more apps faster and consistently together.

  • Create and compose “app building blocks”: UI elements, full features, pages, applications, serverless, or micro-services. With any JS stack.
  • Easily share, and reuse components as a team.
  • Quickly update components across projects.
  • Make hard things simple: Monorepos, design systems & micro-frontends.

Try Bit open-source and free→

Learn more


How to Use localStorage in JavaScript: an Easy Guide was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


Print Share Comment Cite Upload Translate
APA
Justin Graysen | Sciencx (2024-03-29T00:05:15+00:00) » How to Use localStorage in JavaScript: an Easy Guide. Retrieved from https://www.scien.cx/2022/08/25/how-to-use-localstorage-in-javascript-an-easy-guide/.
MLA
" » How to Use localStorage in JavaScript: an Easy Guide." Justin Graysen | Sciencx - Thursday August 25, 2022, https://www.scien.cx/2022/08/25/how-to-use-localstorage-in-javascript-an-easy-guide/
HARVARD
Justin Graysen | Sciencx Thursday August 25, 2022 » How to Use localStorage in JavaScript: an Easy Guide., viewed 2024-03-29T00:05:15+00:00,<https://www.scien.cx/2022/08/25/how-to-use-localstorage-in-javascript-an-easy-guide/>
VANCOUVER
Justin Graysen | Sciencx - » How to Use localStorage in JavaScript: an Easy Guide. [Internet]. [Accessed 2024-03-29T00:05:15+00:00]. Available from: https://www.scien.cx/2022/08/25/how-to-use-localstorage-in-javascript-an-easy-guide/
CHICAGO
" » How to Use localStorage in JavaScript: an Easy Guide." Justin Graysen | Sciencx - Accessed 2024-03-29T00:05:15+00:00. https://www.scien.cx/2022/08/25/how-to-use-localstorage-in-javascript-an-easy-guide/
IEEE
" » How to Use localStorage in JavaScript: an Easy Guide." Justin Graysen | Sciencx [Online]. Available: https://www.scien.cx/2022/08/25/how-to-use-localstorage-in-javascript-an-easy-guide/. [Accessed: 2024-03-29T00:05:15+00:00]
rf:citation
» How to Use localStorage in JavaScript: an Easy Guide | Justin Graysen | Sciencx | https://www.scien.cx/2022/08/25/how-to-use-localstorage-in-javascript-an-easy-guide/ | 2024-03-29T00:05:15+00:00
https://github.com/addpipe/simple-recorderjs-demo