Skip to Content
JavaScript: The Definitive Guide, 6th Edition
book

JavaScript: The Definitive Guide, 6th Edition

by David Flanagan
May 2011
Intermediate to advanced
1093 pages
40h 54m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, 6th Edition

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 types ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: The Definitive Guide, 5th Edition

JavaScript: The Definitive Guide, 5th Edition

David Flanagan

Publisher Resources

ISBN: 9781449393854Errata PageSupplemental Content