How To Use Local Storage Javascript
Editor's note: This post was updated on 29 December 2020.
In this tutorial, we'll prove yous how to use the localStorage
mechanism and Window.localStorage
property and review the basics of web storage in JavaScript.
Nosotros'll comprehend the following in item:
- What is the Web Storage API?
- What is the difference between
sessionStorage
andlocalStorage
? - What is
localStorage
in JavaScript? - Where is
localStorage
stored? - What is
Window.localStorage
? - How does
localStorage
piece of work?-
setItem()
: How to store values inlocalStorage
-
getItem()
: How to get items fromlocalStorage
-
removeItem()
: How to deletelocalStorage
sessions -
clear()
: How to delete all items inlocalStorage
-
key()
: How to get the name of a key inlocalStorage
-
-
localStorage
browser back up -
localStorage
limitations
What is the Web Storage API?
The Web Storage API is a set of mechanisms that enable browsers to store primal-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 admission these values like an object or using the getItem()
method (more than on that later).
What is the difference between sessionStorage
and localStorage
?
The Web Storage API consists of two mechanisms: sessionStorage
and localStorage
. Both sessionStorage
and localStorage
maintain a dissever storage area for each available origin for the duration of the page session.
The main difference between sessionStorage
and localStorage
is that sessionStorage
only maintains a storage expanse while the browser is open (including when the folio reloads or restores) while localStorage
continues to store data afterward the browser is closed. In other words, whereas data stored in sessionStorage
is cleared when the page is airtight, data stored in localStorage
does not expire.
In this tutorial, we'll focus on how to utilize localStorage
in JavaScript.
What is localStorage
in JavaScript?
localStorage
is a belongings that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored in the browser volition persist even after the browser window is closed.
For a visual refresher on how to use localStorage
in JavaScript, check out the video tutorial beneath:
Where is localStorage
stored?
In Google Chrome, web storage information 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/Awarding Support/Google/Chrome/Default/Local Storage
on macOS
Firefox saves storage objects in an SQLite file called webappsstore.sqlite
, which is as well located in the user's contour folder.
What is Window.localStorage
?
The localStorage
mechanism is available via the Window.localStorage
belongings. Window.localStorage
is part of the Window
interface in JavaScript, which represents a window containing a DOM document.
The Window
interface features a broad 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.
How does localStorage
piece of work?
To use localStorage
in your web applications, there are five methods to choose from:
-
setItem()
: Add together key and value tolocalStorage
-
getItem()
: This is how you get items fromlocalStorage
-
removeItem()
: Remove an item by fundamental fromlocalStorage
-
clear()
: Articulate alllocalStorage
-
key()
: Passed a number to retrieve the key of alocalStorage
setItem()
: How to store values in localStorage
Just as the name implies, this method allows you to shop values in the localStorage
object.
It takes 2 parameters: a key and a value. The primal tin can be referenced later to fetch the value fastened to information technology.
window.localStorage.setItem('proper noun', 'Obaseki Nosa');
Where name
is the fundamental and Obaseki Nosa
is the value. Too notation that localStorage
tin can only store strings.
To store arrays or objects, y'all would have to convert them to strings.
To do this, nosotros use the JSON.stringify()
method before passing to setItem()
.
const person = { name: "Obaseki Nosa", location: "Lagos", } window.localStorage.setItem('user', JSON.stringify(person));
getItem()
: How to get items from localStorage
To get items from localStorage, use the getItem()
method. getItem()
allows you lot to access the information stored in the browser'southward localStorage
object.
getItem()
accepts only i parameter, which is the central
, and returns the value
equally a string.
To retrieve a user key:
window.localStorage.getItem('user');
This returns a string with value as:
"{"name":"Obaseki Nosa","location":"Lagos"}"
To use this value, you would have to convert information technology dorsum to an object.
To practice this, we make use of the JSON.parse()
method, which converts a JSON cord into a JavaScript object.
JSON.parse(window.localStorage.getItem('user'));
removeItem()
: How to delete localStorage
sessions
To delete local storage sessions, use the removeItem()
method.
When passed a key proper noun, the removeItem()
method removes that primal from the storage if it exists. If there is no detail associated with the given key, this method will do nothing.
window.localStorage.removeItem('name');
clear()
: How to delete all items in localStorage
Use the clear()
method to delete all items in localStorage
.
This method, when invoked, clears the entire storage of all records for that domain. It does not receive whatever parameters.
window.localStorage.articulate();
cardinal()
: How to go the name of a key in localStorage
The key()
method comes in handy in situations where you need to loop through keys and allows you to pass a number or index to localStorage
to retrieve the name of the key.
var KeyName = window.localStorage.central(alphabetize);
localStorage
browser support
localStorage
as a type of web storage is an HTML5 specification. Information technology is supported by major browsers including IE8. To exist sure the browser supports localStorage
, you can check using the following snippet:
if (typeof(Storage) !== "undefined") { // Code for localStorage } else { // No spider web storage Support. }
localStorage
limitations
As easy every bit it is to use localStorage
, it is also piece of cake to misuse it. The post-obit are limitations, and also means to Not utilise localStorage
:
- Do not store sensitive user information in
localStorage
- It is non a substitute for a server based database as data is only stored on the browser
-
localStorage
is limited to 5MB across all major browsers -
localStorage
is quite insecure as it has no form of information protection and tin exist accessed by whatsoever lawmaking on your web folio -
localStorage
is synchronous, significant each operation chosen would only execute one afterwards the other
With these, nosotros have been armed with the power of localStorage
in our web applications.
LogRocket: Debug JavaScript errors more easily by understanding the context
Debugging code is always a tedious job. Merely the more than y'all understand your errors the easier it is to fix them.
LogRocket allows you lot to understand these errors in new and unique means. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the power to find out exactly what the user did that led to an error.
LogRocket records console logs, folio load times, stacktraces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!
Try information technology for free.
How To Use Local Storage Javascript,
Source: https://blog.logrocket.com/localstorage-javascript-complete-guide/
Posted by: smithbispecephe.blogspot.com
0 Response to "How To Use Local Storage Javascript"
Post a Comment