How to use local storage in javascript

What is local storage
Often you need to maintain a small amount of data for a web application such as a key, current timezone, user logged time etc. but you do not want to bear an overhead of sending this data to server or saving it in a database.
Solution is to use local storage of the browser.

What is local storage
HTML5 introduced the concept of web storage where you can store data inside the browser. This data remains forever till it is not cleared even after the browser window is closed.
Data in browser’s local storage is set and retrieved using javascript and it is stored in the form of key-value pairs.
Following are some important aspects regarding local storage

  1. Data stored in local storage has no expiration duration.
  2. Data stored in local storage is bound to a domain name and can be accessed by web paged loaded inside the same domain. Thus, data stored for will be accessible to pages that belong to it. Pages of cannot access it.
  3. Values stored in local storage are not sent to server. You need to explicitly retrieve them and then send to the server.
  4. With local storage, you can store 5 to 10 MB of data.

How to use local storage
Browser’s storage can be accessed using window.localStorage object of javascript. You can also directly call localStorage object since window object is implicit.
This object stores the data in key-value pairs. There are 2 ways in which data can be stored in localStorage object.
1. Using built-in methods
localStorage object has following methods that are used to save and get data from local storage.
setItem: This method is used to save data into local storage. It takes two arguments with first argument as the key and second as the value to be stored. Note that it stores both key and value in string format.
If the key is not a string, then this method will raise an error while if the value is not a string then it will be converted to string format.
getItem: This method is used to get the value stored against a key in local storage. It takes a single argument which is the key.
If the specified key-value mapping is not present, then it returns null.

// save in local storage
window.localStorage.setItem('name', 'codippa');
// get from local storage
let data = window.localStorage.getItem('name');
console.log(data);  // prints codippa

2. Using key access

As stated previously, localStorage object stores data in key-value pairs. It is just like a normal javascript object which has key-value pairs.
For assigning a value to a key in javascript object, below notation is used

objectname[‘key’] = value

If the key is not present, then it is created. If the key is already present, then its value is overwritten. Data in localStorage also can be saved using similar syntax.

To know better about javascript objects, refer this.

For retrieving the value corresponding to a key, same syntax is used except that the value is assigned to some variable as

let value = objectname[‘key’]


// create a key-value pair
localStorage['name'] = 'codippa';
console.log(localStorage['name'];   // prints codippa

Removing item from local storage
For removing a particular key-value pair from local storage, use removeItem method of localStorage object. This method takes a key and removes the key-value mapping corresponding to the supplied key from local storage.
If you want to remove all key-value pairs or empty local storage, then use clear method of localStorage object. This method takes no arguments and removes all the data from local storage.

// remove key-value pair with key as 'name'
// empty local storage

Save arrays or json objects
As mentioned earlier, a localStorage object can only store values in string format. Thus, if you want to save an array or a json object in local storage, convert it to string using JSON.stringify method and save.
When retrieving the data, use JSON.parse method to convert them into their actual type. Example,

// create a json object
const language = {'name': 'javascript', 'type': 'web'};
// save it in local storage
localStorage.setItem('language', JSON.stringify(langauge));
// create an array
const numbers = [1, 2, 3, 5];
// save it in local storage
localStorage.setItem('numbers', JSON.stringify(numbers));
// get back json object
const json = JSON.parse(localStorage.getItem('language'));
// access a key
console.log(json['name']);  // prints javascript
// get back array
const array = JSON.parse(localStorage.getItem('numbers')); 
// access second array element
console.log(array[1]);   // prints 2

Get total number of saved values
If you want to know the total number of key-value pairs stored in localStorage object, then it has a length property which can be used.
Example, localStorage.length in above example will return 2.

Let’s tweak in

  1. Local storage can only be used to store limited amount of data.
  2. It can not be used as a replacement of server side database.
  3. Do not store sensitive information in local storage such as user names, passwords as the contents of localStorage are clearly visible since they are stored in plain text and not encrypted.
  4. Data stored in localStorage remains even after the browser window is closed.
  5. Local storage is different from cookies in that
    • Cookies can store small amount of data(4 KB max) as compared to local storage.
    • Cookies are sent to the server with every request
    • Cookies expire(or get deleted) automatically after some specified time.

Hope this post successfully demonstrated the concept and usage of local storage in browsers. Hit the clap below to appreciate the content and motivate us to write more such stuff.


Mark Your Impression

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.