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 localStorage property is a property on the window object, therefore it's not available on the server. Copied! If you got the error in the browser, make sure that you have not misspelled the localStorage keyword (should be camelCase).
Using the localStorage. The localStorage. getItem() method takes the key as an argument and returns the key's value. if a key doesn't exist it returns the null .
The getItem() method returns value of the specified Storage Object item. The getItem() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorage object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With