Local Storage

Local storage allow developers to create persistent data within the browser by means of key value pairs. The benefit of this is that it allows the data to persist even after the browser window has closed.

One thing to note, the data is constrained to the local browser that the page has being loaded from. And that data is sandboxed to that specific domain. For example: https://yourSite.com would be different to http://yourSite.com

In the past cookies were used, however they were limited because of their 5kb file size. Local storage allows up to 5MB of data.

The api is a fairly simply one to use, it consists of four methods.

  1. setItem()
  2. getItem()
  3. removeItem()
  4. clear()
  5. key()
  6. length

setItem()


	> localStorage.setItem('id', 'one');
	> localStorage.setItem('age', 'mystery');
	> localStorage.setItem('name', 'robert');
            
or

	> localStorage.id = 'one'

					 
which yields

	> localStorage
	  Storage {age: "mystery", id: "one", name: "robert", length: 3}
          

getItem()


	> localStorage.getItem('id')
		"one"
						
or

	> localStorage.age
	    "mystery"
				  

removeItem()


	> localStorage.removeItem('age')
						

	> localStorage
		Storage {id: "one", name: "robert", length: 2}
						

clear()


	> localStorage.clear();
						

	> localStorage
	  Storage {length: 0}
						

key()


	> localStorage.key(1);
						

	> 'id'
						

length


	> localStorage.length;
						

	> 3
						
How is this useful for me!?!
You can set localStorage values to variables.

	var age = localStorage.age;
		        	

	> age
	"mystery"
		        	
You can pass an object into Local Storage

	var profile = {
	  'name': {
	          'first': Robert,
	          'last': James},
	   'age': 10
	}

	localStorage.setItem('id', JSON.stringify(profile));
		        	

	> localStorage
	Storage {profile: "{"name":{"first":"Robert","last":"James"},"age":"10"}", length: 1}
		        	

	
			        

	> var age = document.querySelector('age').value;
	> localStorage.setItem('age', age);
		        	
There are libraries to help work with local storge.

Thank You

Robert James @bkrjames