st88 st88 - 7 months ago 14
Javascript Question

What are the purpose of the getter-, setter-methods of the localStorage-object?

The localStorage-object has get- and set-methods for reading / writing data.

Now I've seen in some code that one can access the stored data like with a normal JavaScript-object.

For example:

localStorage['mainColor'] = '#efefef';


Obviously are the data kept as public-properties. But then the get-, set-methods make no sense ... ?:|

So I ask myself:
What's the purpose of these getter-, setter-methods?

Answer

Local storage, as well as other forms of web storage, follows the Web storage specification.

In this specification, a clear interface is defined to use this API that defines this behavior. Theoretically this API could be used by other languages that JavaScript too, which may not have proper access to these dynamic properties, or in which using the methods is more common.

Practical uses in JavaScript:
You could use getItem to get a key value with the same name as one of the methods.
Also, and probably more important, getItem, as well as removeItem, silently ignore if the item doesn't exist, which makes using them easier in many cases.

One other possible difference, although I haven't tested this. The specification says: "When the setItem(), removeItem(), and clear() methods are invoked, events are fired on the Window objects of other Documents that can access the newly stored or removed data". So maybe this event is invoked when you use setItem('prop'), but not when you use ['prop'].