Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 876
jaySon Avatar asked Apr 08 '15 15:04

jaySon


People also ask

Why is my localStorage undefined?

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).

What does localStorage getItem return if not found?

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 .

What does localStorage getItem return?

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.


1 Answers

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
like image 128
Alnitak Avatar answered Oct 20 '22 04:10

Alnitak