How do i save javascript data?

How to store data with localStorage and sessionStorage. The benefits of each, and when you should use one instead of the other

How do i save javascript data?

Photo by Raymond Rasmusson on Unsplash

localStorage and sessionStorage are web storage objects that you can use to save information on the browser. Data added to sessionStorage can survive trough page reloads and localStorage keeps your data even with the browser closing and reopening.

These storages offer some interesting features. They differ from cookies in not being sent to server with each request, which allows it to be bigger (most browsers have at least 2 Mb). Everything is done trough JavaScript, there is no meddling with data by the server trough HTTP headers. Every storage is defined by the triplet domain, protocol, port, so data from one application can't be accessed by another.

These storage objects offer the same methods and properties:

  • setItem(key, value) store key/value pair.
  • getItem(key) gets the value by key.
  • removeItem(key) remove the key and value.
  • clear() delete everything from the storage.
  • key(index) get the key from a given position.
  • length the count of stored items.

To understand this a little better, let's go over some examples.

localStorage

Data on localStorage is shared between all browser windows from the same origin (remember the triplet: domain, protocol, port). Also, it is kept locally on disk, hence the name, so it will survive even trough an OS restart.

As long as you keep the triplet consistent, you can store data with localStorage.setItem('test', 1); on one window and read it with localStorage.getItem('test'); on another. Note that you can change the URL, only the domain has to be the same.

Another interesting fact is that the same information will be available to all windows of the same triplet. Changes on one will be reflected on the other.

Accessing Data on localStorage

You can use the methods listed above to retrieve the data or use an object like notation. Object notation is clearer, but it opens the door to some bugs. Here you will see what I mean.

On line 12 we try to add a value of 5 to the key 'length', but using object notation JavaScript thinks we are referring to the property length and gives us an error.

On line 15 we do the same thing, but since we are using localStorage's setItem() method, JavaScript knows we want to set the value for the 'length' key.

Listing All Keys

You have more than one way to loop over all keys on localStorage, but it is not an iterable, so they are not straight forward. You can do it like a regular array, using for ... in , and using the keys property.

To iterate as an array use something like this:

If you prefer using a for ... in keep in mind that it will also get some of the built in stuff that localStorage has, like methods and properties. To work around that we must add a check to remove built ins.

The easier way is to use the keys and get all keys from the object. Because keys is at the object level it won't list the methods and attributes from the prototype (I have another article on Medium with an explanation of prototypes in JavaScript).

localStorage Only Deals With Strings

That is right, both key and values are always strings. Even if you try to set a numeric value, like we did above, it will be cast to string.

More complex types can be stored with a workaround.

sessionStorage

sessionStorage has the same methods and properties as localStorage, but it only stores data while the session is open. The information will persist between refreshes, but not if you close the browser. For that reason sessionStorage is used less often than localStorage.

Storage Event

Whenever an update happens to either sessionStorage and localStorage, an event is triggered on all windows that have access to the storage, except the one that caused it.

The following are properties of this event:

  • key the key that was changed (null if .clear() is called).
  • oldValue the old value (null if the key is newly added).
  • newValue the new value (null if the key is removed).
  • url the url of the document where the update happened.
  • storageArea either localStorage or sessionStorage object where the update happened.

Conclusion

Both methods of storing data on the browser have their uses. sessionStorage is more limited, only storing data for the current window. localStorage has more uses, because the data is kept even when the browser closes.

If you liked this article, please share with your friends and consider following me on Medium.

Build composable frontend and backend

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →

How do i save javascript data?

Learn More

How do I save information in JavaScript?

Store Data in the Browser with JavaScript.
setItem(key, value) store key/value pair..
getItem(key) gets the value by key..
removeItem(key) remove the key and value..
clear() delete everything from the storage..
key(index) get the key from a given position..
length the count of stored items..

How can we store data in JavaScript without database?

You can use web storage. From W3Schools: With web storage, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request.

How do I save JavaScript in HTML?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the tags in your HTML document.

How data is stored in database in JavaScript?

Storing Data into the Database.
In the app.js file, we will use the save() method for saving the post created in the post() method. ... .
Now, we will override the database name in the connection string because we are using a default database name. ... .
Now, we will create a new post entry or document..