JavaScript
Storing data with JSON
Learn to store objects and arrays in localStorage as JSON.
localStorage stores only text
localStorage stores only text. If you save a number, JavaScript converts it to a string automatically, and you read back a string.
localStorage.setItem('count', 42);
const back = localStorage.getItem('count');
Here the number 42 is saved, but getItem returns the string '42'. If you try to save an object, you get '[object Object]' because objects cannot be turned into text directly.
Turn an array into text and back
To save an array in localStorage, you first turn it into text. The join method combines every element of the array with a separator into a single string.
const names = ['Alex', 'Mara'];
localStorage.setItem('names', names.join(','));
When reading back, the split method breaks the text at the separator and turns it into an array. But since getItem returns null when nothing is saved, check first.
Exercise Save an array as text and read it back
Turn the names array into text with .join(',') and save it under the 'names' key. Then read it back with getItem and turn it into an array with .split(',') in a back variable.
Show example solution
localStorage.setItem('names', names.join(','));
const back = localStorage.getItem('names').split(',');
Test yourself
-
If you save an object to localStorage, what does getItem return?
localStorage.setItem('user', { name: 'Alex' });
const back = localStorage.getItem('user');
- The { name: 'Alex' } object
- Alex
- It throws
- [object Object]
Show answer
[object Object] — Correct! The object is turned into the text '[object Object]'.
-
Turn the array into text
const text = names.____(',');
Show answer
const text = names.join(',');
-
Match the conversion methods
- names.join(',')
- Turns array into text
- text.split(',')
- Turns text into array
- String(42)
- Turns number into text
-
After setItem('count', 42), what type does getItem('count') return?
localStorage.setItem('count', 42);
const back = localStorage.getItem('count');
- string
- number
- boolean
- object
Show answer
string — Correct! localStorage always returns text; 42 becomes '42'.
Next lesson: Clearing storage