4

Throughout the web I've seen 3 approaches to save and retrieve data from localStorage:

//As an array
localStorage["key"] = "value";
var value = localStorage[key];

//As an object, using properties
localStorage.key = value;
var value = localStorage.key;

//As an object, using getter and setter functions
localStorage.setItem("key", "value");
var value = localStorage.getItem("key");

From what I know the first two are equivalent, as an array in JavaScript is treated like an object.

The third one seems the best approach because using getters and setters enables encapsulation of the function's logic, and also extension.

I'm hoping to get some more insight on this, can someone advise?

EDIT: The reason for this question comes from the fact that localStorage is more than just an array so I'm looking for opinions explicitly targeting localStorage and it's implementation.

madth3
  • 7,275
  • 12
  • 50
  • 74
Telmo Marques
  • 5,066
  • 1
  • 24
  • 34
  • 1
    I think you are already completely correct in your understanding. – Brian Hannay May 29 '13 at 23:19
  • @AdamWaite, when there is more than one way to approach something it always matters. `localStorage` isn't just an array, it's an entire spec (http://www.w3.org/TR/webstorage/), so maybe it deserves some more insight. – Telmo Marques May 29 '13 at 23:23
  • I would use the first or third if the key is a variable, the second if it's hard-coded into the application, because object notation is more readable. – Barmar May 29 '13 at 23:31
  • Well I guess that it comes down to what setItem and getItem actually do. The other two are equivalent. Personally I'd go through the accessors but to be honest if it works and satisfies the spec then whatever goes for me! – Adam Waite May 29 '13 at 23:31
  • Calling localStorage.getItem("key") on an key that does not exist will return null. I'm not sure what calling localStorage["key"] will do if the key does not exist, but it may throw an error. Also when working with localStorage be sure to check if the browser supports local storage, you can do this by wrapping your localStorage code in a Modernizr check like `if(Modernizr.localStorage) { localStorage.setItem("key", "value"); }` – Dropzilla May 29 '13 at 23:32
  • @PherricOxide, I'm surprised I didn't found that before... thanks! – Telmo Marques May 29 '13 at 23:35

3 Answers3

3

Your understanding seems totally correct to me. What may be confusing you is the strange nature of javascript. In javascript everything is an object and every object can essentially be treated like a hashmap, thus your first two examples are equivalent. The last two examples are also effectively equivalent as they are just function members of the local storage object. Since all the examples have the same effect I would say that the most important thing is to remain consistent in your code to make it more readable.

Keep in mind that an array is also an object and can be treated as such

aaronman
  • 18,343
  • 7
  • 63
  • 78
1

The difference between bracket access and dot access to object properties is just a convenience of the language. The difference between direct property access and using getter/setter methods is interesting though.

The spec says:

"The supported property names on a Storage object are the keys of each key/value pair currently present in the list associated with the object."

That says to me that direct access is perfectly legitimate. i.e. all user-agents implementing the spec should support it.

As for which is better. I'm not sure it's the purpose of the specification to say so. It can't say how a particular user agent implementation might be biased toward one method or the other due to its internal workings. The spec really just defines the interface.

For example - if direct property access in a particular user agent simply invoked the getter/setting methods internally, then perhaps using those methods would have a performance benefit.

Personally I'd use the methods, but abstract the functionality in my application to a simple function that I can swap out if I need to later on. e.g:

function getLocal( key ){
    return localStorage.getItem(key);
}

If for some reason I find a problem with this, or need to support older browsers (say, falling back to regular cookies) I can just alter my app in one place. I know that wasn't your question, but there it is.

Tim
  • 8,036
  • 2
  • 36
  • 52
0

This is how I use it.

function setLocalObj(id, obj){
    if(id && obj)
        localStorage[id] = JSON.stringify(obj);
}

function getLocalObj(id){
    if(localStorage[id])
        return JSON.parse(localStorage[id]);
}

function removeLocalObj(id){
    if(localStorage[id])
        localStorage.removeItem(id);
}


var myObj = {
    'val':10,
    'str': 'hi there'   
}
setLocalObj('myObj', myObj);
gkiely
  • 2,987
  • 1
  • 23
  • 37