jaySon jaySon - 5 months ago 22
Javascript Question

Why is localStorage["..."] undefined, but localStorage.getItem("...") is null?

Last time I checked, the following two lines returned

true
:

null == localStorage["..."];
null == localStorage.getItem("...");


Same applies when replacing
null
with
undefined
.
So the first question is, why are there two ways to address the localStorage? And why does

localStorage["..."]


return
undefined
while

localStorage.getItem("...")


returns
null
?

Do I need to take care of that when developing JS?

Answer

The Web Storage Specification requires that .getItem() returns null for an unknown key.

Note however that .getItem() and .setItem() are specifically defined in the IDL as being the designated getter and setter for the Storage interface, and therefore they're also fully supported ways of accessing the contents of the storage.

However the [] syntax is more akin to a normal object and/or array property getter, and like those returns undefined for an unknown property name.

The reason not to use [] syntax is that it will operate on object properties first and will quite happily allow you to overwrite real properties and methods of the localStorage object, c.f:

> localStorage['getItem'] = function() { return 0 }
> localStorage.getItem('getItem')
0