9

One of the first results from a Google search says that this syntax is to be used for localStorage:

localStorage.lastname="Smith";

MDN uses .setItem() and .getItem(), I suppose so that if the browser doesn't support localStorage, then you can add it using the technique defined there.

But since my program is only running on iOS, I guess my question is:

Is it ok to use

localStorage.lastname="Smith";

instead of:

window.localStorage.setItem("lastname","Smith");
4
  • 10
    Well, I wouldn't trust w3schools, especially when it comes to best practices... Dec 19, 2013 at 18:53
  • 1
    If you're only concerned about one OS, why not simply test it on that OS. That would remove any doubt about the accuracy of third party sources. Dec 19, 2013 at 19:27
  • I would follow the specification: w3.org/TR/webstorage/#storage If the device doesn't support the spec, I would then use a polyfill to keep my code consistent with the spec. Dec 19, 2013 at 19:50
  • 1
    If getItem and setItem work now, and are the standard - then I would stick with them. Whilst object syntax may work on iOs now, you cannot guarantee that will continue to be the case in the future - a standard is much more likely to enjoy continuing support.
    – pwdst
    Jan 6, 2014 at 20:45

1 Answer 1

5

Though both methods are valid JavaScript,

localStorage.lastName = "Smith";

assigning a value directly like above to a key can sometimes result in property conflicts.

window.localStorage.setItem("lastname","Smith");

On the other hand is a better practice to get into. MDN and most other resources recommend this method when working with Local-storage.

Not the answer you're looking for? Browse other questions tagged or ask your own question.