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()
returnsnull
for an unknown key.Note however that
.getItem()
and.setItem()
are specifically defined in the IDL as being the designatedgetter
andsetter
for theStorage
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 returnsundefined
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 thelocalStorage
object, c.f:In javascript you always get an
undefined
value for keys that does not exist inside an object.In localStorage
.getItem
is a method who does check keys inside the localStorage object and returnsnull
if not found.Don't blame javascript, it's just the localStorage object behaviour
localStorage["..."]
is invalid usage of localstorage. You are trying to access methods of thelocalstorage
object, rather than accessing actual database.You have to use
and
methods to access storage database.