O'Reilly logo

JavaScript: The Definitive Guide, 6th Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

localStorage and sessionStorage

Browsers that implement the “Web Storage” draft specification define two properties on the Window object: localStorage and sessionStorage. Both properties refer to a Storage object—a persistent associative array that maps string keys to string values. Storage objects work much like regular JavaScript objects: simply set a property of the object to a string, and the browser will store that string for you. The difference between localStorage and sessionStorage has to do with lifetime and scope: how long the data is saved for and who the data is accessible to.

Storage lifetime and scope are explained in more detail below. First, however, let’s look at some examples. The following code uses localStorage, but it would also work with sessionStorage:

var name = localStorage.username;         // Query a stored value.
name = localStorage["username"];          // Array notation equivalent
if (!name) {
    name = prompt("What is your name?");  // Ask the user a question.
    localStorage.username = name;         // Store the user's response.
}

// Iterate through all stored name/value pairs
for(var name in localStorage) {           // Iterate all stored names     
    var value = localStorage[name];       // Look up the value of each one
}

Storage objects also define methods for storing, retrieving, iterating, and deleting data. Those methods are covered in Storage API.

The Web Storage draft specification says that we should be able to store structured data (objects and arrays) as well as primitive values and built-in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required