Last time I checked, the following two lines returned true
:
null == localStorage["foo"];
null == localStorage.getItem("foo");
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["foo"]
return undefined
while
localStorage.getItem("foo")
returns null
?
Do I need to take care of that when developing JS?
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
localStorage["..."]
is invalid usage of localstorage. You are trying to access methods of the localstorage
object, rather than accessing actual database.
You have to use
localStorage.getItem("...")
and
localStorage.setItem("...")
methods to access storage database.
In javascript you always get an undefined
value for keys that does not exist inside an object.
a = {}; //new object
alert(a["test"]); // you get 'undefined' because "test" keys is not found
In localStorage .getItem
is a method who does check keys inside the localStorage object and returns null
if not found.
Don't blame javascript, it's just the localStorage object behaviour