javascriptgoogle-chromelocal-storagedeveloper-toolsweb-storage

localStorage['key'] vs localStorage.setItem('key', value)


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.

    > 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