Lesson 5 - Local Storage API, Storing and Retrieving Simple Data, Arrays, Associative Arrays, and Objects
The storage property has two main types; localStorge and sessionStorage. They behave much the same way except sessionStorage is emptied at the end of each session, and localStorage persists accross multiple sessions. This is a big improvement over the storage of the past, which was mostly done with cookies. An example of localStorage would be an online shopping cart. If you have ever added something to your cart, then come back to the site later to find the item still in your cart, this is most likely done utilizing localStorage.
Syntax
To save data
localStorage.setItem("itemName", "value")
Example:
localStorage.setItem("username", "Bill");
To access stored data
alert("itemName = " = localStorage.getItem("itemName"));
Example:
alert("username = " + localStorage.getItem("username"));
The alert output would be "username = Bill"
Is it supported?
web storage is not always supported so before using you must check to ensure that web storage (local storage) is available.
if (typeof(Storage) !== "undefined"){ //code to execute}
else{
//code to execute}
This is read as if type of storage is not undefined. As long as the type of storage is not undefined you can use local storage for your page.
Objects
This first example is an example of creating an API object. We set the itemName and the value. Here you can create your own object and store your favorite color.Favorite Color:
Now we can retrieve your favorite color from local storage.
Arrays
We can do the same thing with Arrays. But local storage can only support stings. We can convert to a string using JSON.stringify() and convert back using JSON.parse. Lets create an array with your three favorite colors.0:
1:
2:
Now lets see out new array. Remember Arrays are numbered with the first item as number 0. So which array item do you want to see? (choose 0,1,2)
Associative Arrays
Associative Arrays are arrays with names instead of numbers assigned to each value. Lets build an associative array right now. Lets make a list of your favorites.Name:
Food:
Music:
Movie:
Insect:
Now lets display your associative array. Just click the button to see the stored result.
Name: Food: Music: Movie: Insect: