Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to use localStorage in JavaScript

Programming Bytes

localStorage is a browser storage area where we can store data as key-value pairs in the localStorage.

localStorage features

  • localStorage is separate for each origin (for example, Google and Facebook have separate localStorage objects, so we cannot access the localStorage object of Facebook from Google).

  • The data stored in localStorage is available to all tabs and windows of the same websiteorigin.

  • The data will not be removed when the browser restarts or the computer powers off.

Methods available in localStorage

The following methods are available in the localStorage object:

  • setItem(key, value): save data in localStorage
  • getItem(key): get the value
  • removeItem(key): remove data of the key
  • clear(): clear localStroage
  • key(index): get the key on the index
  • length: return the number of keys

Example

localStorage.setItem('name', "Ranjith");
localStorage.setItem('age', 25);
localStorage.setItem('height', 170);
localStorage.setItem('weight', 70);

// length
localStorage.length; // 4

// get
localStorage.getItem('age'); // "25"

// remove
localStorage.removeItem('weight');  

//length 
localStorage.length; // 4

// if the key not present then, null will be returned 
localStorage.getItem('weight'); //null

// key 
localStorage.key(0); //name

// clear 
localStorage.clear(); 

//length 
localStorage.length; // 0

How are values stored?

Both the key and value will be stored as String. When we try to save an object, it will be stored as “[object object]”:

localStorage.setItem("obj", {});
localStorage.getItem("obj"); // [object Object]

To store an object in localStorage, we can convert the object to JSONString and store it. Upon accessing the data, we can parse the string to a JSON object:

let user ={
    name : "JavaScript Jeep",
    age : 23
};
let userStr = JSON.stringify(user);

localStorage.setItem("user", userStr);

let parsedUser = JSON.parse(localStorage.getItem("user"));
parsedUser; // {name: "JavaScript Jeep", age: 23}

Perform operations

We can get and set key-value the same way we do in objects:

// set 
localStorage.name = "Raju";

// get
localStorage.name; // "Raju"

// remove
delete localStorage.name;

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring