Skip to Content
JavaScript Cookbook, 3rd Edition
book

JavaScript Cookbook, 3rd Edition

by Adam D. Scott, Matthew MacDonald, Shelley Powers
July 2021
Intermediate to advanced
535 pages
11h 55m
English
O'Reilly Media, Inc.
Content preview from JavaScript Cookbook, 3rd Edition

Chapter 14. Data Persistence

We can animate and interact, stream, play, and render, but we always come back to the data. Data is the foundation on which we build the majority of our JavaScript applications. In the first part of the book we worked with the JavaScript languages standards for data types, in Chapter 13 we fetched data from a remote source, and in Chapter 20 we’ll work with data on the server, manipulating data using APIs and data sources. Data and JavaScript, friends forever.

In this chapter, we’re going to look at ways we can persist data with JavaScript in the browser using cookies, sessionStorage, localStorage, and IndexedDB.

Persisting Information with Cookies

Problem

You need to read or set the value of a browser cookie.

Solution

Use document.cookie to set and retrieve cookie values:

document.cookie = 'author=Adam';
console.log(document.cookie);

To encode strings, use encodeURIComponent, which will remove any commas, semicolons, or whitespace:

const book = encodeURIComponent('JavaScript Cookbook');
document.cookie = `title=${book}`;
console.log(document.cookie);

// logs title=JavaScript%20Cookbook

Options can be added to the end of the cookie value and should be separated with a semicolon:

document.cookie = 'user=Abigail;  max-age=86400; path=/';

To delete a cookie, set an expiration date for the cookie that has already occurred:

function eraseCookie(key) {
  const cookie = `${key}=;expires=Thu, 01 Jan 1970 00:00:00 UTC`;
  document.cookie = cookie;
}

Discussion ...

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

Learning JavaScript, 3rd Edition

Learning JavaScript, 3rd Edition

Ethan Brown
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9781492055747Errata PageSupplemental Content