Debialo
Debialo

Reputation: 53

"undefined" before actual value in LocalStorage

This is the code I use:

localStorage["FSS"] += JSON.stringify(favSongs);
localStorage["FSTS"] += JSON.stringify(favSongTitle);
localStorage["FIS"] += JSON.stringify(favImages);

But when I retrieve the values I get this:

For FSS: undefined["0t0FGyhB6C8"]

For FSTS: undefined["SONIC SYNDICATE - Denied (OFFICIAL MUSIC VIDEO)"]

For FIS: undefined["https://i.ytimg.com/vi/0t0FGyhB6C8/mqdefault.jpg"]

enter image description here

I don’t understand how and where the undefined comes from and how I remove it to log the results on my screen (now when I log it it says undefined as well).

Upvotes: 0

Views: 559

Answers (1)

ssube
ssube

Reputation: 48327

The undefined is what was already in localStorage:

document.getElementById('existing').textContent = localStorage[Math.random().toString()];

Because you use the foo += bar syntax, the script will:

  1. Get the existing value of foo
  2. Perform type coercion to make foo and bar compatible
  3. Append bar to the existing value
  4. Assign the combined value back to foo

If foo already contains undefined...

This appears to be an artifact of accessing the localStorage properties via the map accessor. If you used the getItem method, you would receive null instead of undefined.

Since you're working with JSON, the simple string concatenation (string +=) won't work even if you already have a value. You would end up with ['foo-album']['bar-album'], which is not valid. I would recommend getting the existing item or an empty array, appending your new item, then replacing the stored value:

var prev = localStorage.getItem('FSS') || '[]'; // get the existing value or the string representing an empty array
var data = JSON.parse(prev); // parse into an object
data.push('New Album');
localStorage.setItem('FSS', JSON.stringify(data)); // convert back to JSON and set

Upvotes: 3

Related Questions