Window localStorage Attribute

Definition and Usage

The localStorage and sessionStorage attributes allow key/value pairs to be saved in web browsers.

The localStorage object stores data without an expiration date. Data is not deleted when the browser is closed and will be available the next day, week, or even a year later.

The localStorage attribute is read-only.

Tip:See also sessionStorage attribute, which stores session data (data is lost when closing the browser tab).

Instance

Example 1

Create a localStorage name/value pair with name="lastname" and value="Smith", then retrieve the value of "lastname" and insert it into the element with id="result":

// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

Try it yourself

Example 2

The following example calculates the number of times a user clicks a button:

if (localStorage.clickcount) {
  localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
  localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";

Try it yourself

Syntax

window.localStorage

The syntax for saving data to localStorage:

localStorage.setItem("key", "value);

The syntax for reading data from localStorage:

var lastname = localStorage.getItem("key);

The syntax for deleting data from localStorage:

localStorage.removeItem("key);

Technical Details

Return Value: Storage Object

Browser Support

The numbers in the table specify the first browser version that fully supports this property.

Properties Chrome IE Firefox Safari Opera
localStorage 4.0 8.0 3.5 4.0 11.5