Manipulating localStorage with JavaScript!

  • Favourite
Average Star Rating is 4.6 from the Total 5 Ratings

Local Storage is a storage system built into browsers, it helps to store various information on the client side. Local storage is better than cookies, up to 5MB data can be stored. Even though, local storage only stores string. However, using JSON.stringify() method we can store complex JavaScript objects such as JavaScript array, object literal along with their syntactical format. For example for a shopping cart we can have a key called cart and the value could be product details as an object literal. Also the cart will still be there when we close the browser! 

As string: 

**cart [{"product_id":"4","name":"Desktop","price":166.66,"qty":2,"total":333.32,"product_image":"desktop.png"}]**

All we need is JSON.JSON.stringify() method while setting the key value in localStorage and JSON.parse() method to red it back as given below.

/* Declare an empty array */ 
const cart = []; 

/* Push a product object literal in cart array */

/* Set the cart array as string to localStorage 
   using JSON.stringify() method.

/* Get the cart string as a JS array from localStorage 
   using JSON.parse() method.
cart = localStorage.getItem(JSON.parse(cart))

/* Console log the array. */

If its a single value as.

var username = "Nick";
localStorage.setItem("Username", username);
** Username "Nick" **

There are few methods we can use.

// To set key value with JSON.stringify
localStorage.setItem(key, JSON.stringify(value)); 

// To get key with JSON.parse()

// To remove the desired key

// to clear all the localStorage items for the application.

If we want to see the localStorage then we can go to inspect window as below.


Below is a fiddle for a simple program using all these methods together.

Be the first to make a comment!