Generic placeholder image

VLE

Access virtual learning system

View details »

Blog image

BLOG

Access our blog

View details »

php_logo.png

PHP

Access PHP tutorials

View details »

html_logo.png

HTML

Access HTML tutorials

View details »

jquery_logo.png

jQuery

Access jQuery tutorials

View details »

programming_logo.png

Programming

Access Programming tutorials

View details »

web development_logo.png

Web Development

Access Web Development tutorials

View details »

javascript_logo.png

JavaScript

Access JavaScript tutorials

View details »

JavaScript

Manipulating localStorage with JavaScript!

  
  • Favourite
Average Star Rating is 4.7 from the Total 6 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 */
cart.push({"product_id":"4",
            "name":"Desktop",
            "price":166.66,
            "qty":2,
            "total":333.32,
            "product_image":"desktop.png"}
        );

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

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

/* Console log the array. */
console.log(cart)

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()
localStorage.getItem(JSON.parse(key)) 

// To remove the desired key
localStorage.removeItem((key))  

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

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

local_storage 

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


Be the first to make a comment!