Search code examples
javascriptgoogle-chromelocal-storagedeveloper-toolsweb-storage

localStorage.property vs localStorage['property']


Is there a difference between writing localStorage['key'] = value or localStorage.setItem('key', value)?

I saw this question marked as duplicate but within Developer Tools the behavior of both notations is different: the bracket notation does not seem to serialize to a string.

For instance:

> localStorage['key'] = [1,2,3]
[1, 2, 3]
> localStorage.setItem('other', [4,5,6])
undefined
> localStorage.key
[1, 2, 3]
> localStorage.other
"4,5,6"
> localStorage.key.length
3
> localStorage.other.length
5

Can anyone explain that difference in behavior? Can I use the bracket notation and forget about always serializing to JSON?


Solution

  • In general, see localStorage - use getItem/setItem functions or access object directly? - you can use properties the same way as getItem/setItem. Both ways will stringify the values automatically.

    Unless…
    you are using one of the predefined methods' names, like of .key(). That is calling for trouble.

    • Opera and Firefox will store the value in the localStorage, and return the string when the .key is subsequently accessed.
    • Chrome, on the other hand, will just overwrite the method on the localStorage object. No stringification happens, and you just will get the object you did put there. It will not be stored.

    > localStorage.key
    function(){ … }
    > localStorage.key = [1,2,3]
    [1,2,3] // the rvalue
    
    Opera> localStorage.key
    "1,2,3"
    Opera> localStorage.length
    1
    
    Chrome> localStorage.key
    [1,2,3]
    Chrome> localStorage.length
    0