Reputation: 4760
If I do this:
localStorage['a'] = undefined
alert(localStorage['a'] || 20)
"undefined" is alerted - WHY?
var a = undefined
alert(a || 20)
now 20 is alerted.
localStorage.clear()
alert(localStorage['a'] || 20)
here 20 as well... and I checked localStorage['a'] is undefined... just like in the first case when I set it to undefined manually... so why different results?
Upvotes: 2
Views: 301
Reputation: 382454
localStorage stores strings and converts what you pass to strings, so
localStorage['a'] = undefined
sets the string "undefined"
as value in localStorage. It doesn't remove the key and it doesn't set its value as undefined
.
And of course "undefined"
isn't falsy so "undefined"||20
is "undefined"
.
To remove a value, use
localStorage.removeItem('a');
As an aside be careful to the fact that if you set
localStorage['a'] = 20
then you don't get 20
when calling localStorage['a']
but the string "20"
. When you want to get a not null number with a default value, you may do this :
var num = parseInt(localStorage['a'])||20;
Upvotes: 5