Getting an Array from Local Storage with Javascript

  • Estimated read time: 1 min read
  • Written by Chad Campbell on Feb 15th 2012

The local storage feature in HTML gives you a powerful alternative to the traditional cookie. This option lets you store complex data locally on the user's browser. While retrieving a string value can be easy, getting a more complex structure, like an array requires a bit more.

Retrieving an Array from Local Storage

If you save an array to local storage the way Ecofic recommends, it will be stored as a string. To get it back into a usable form, you can use the complementary function JSON.parse. A sample is shown here:

var savedString = localStorage.getItem('collectionKey');
var savedCollection = JSON.parse(savedString);

Its important to recognize that "getItem" will return null if the key isn't in storage. Because of that, you may want to add an additional check. Regardless, the process of using local storage involves serializing / deserializing. This process is leveraged via the JSON.stringify and JSON.parse methods.​


comments powered by Disqus

Chad Campbell
Chad Campbell

Chad is an independent software professional. He has been named a Microsoft MVP five times. His books have been translated into multiple languages and distributed worldwide. He holds a computer science degree from Purdue University, where he also studied psychology.

Chad has built sites, apps, frameworks, libraries, and platforms using Java, .NET, and Node. He's ran his own startups and has created software for Fortune 100 companies. In short, Chad knows how to create software. From ideation to delivery. From start-to-finish.

Follow Chad Online