3

Possible Duplicate:
JavaScript property access: dot notation vs. brackets?

I'm a total newbie to chrome extensions. I know Java but Javascript is something entirely different.

I would like to ask what is the difference between localStorage["something"] and localStorage.something?

The square bracket vs dot.

Community
  • 1
  • 1
bland.life
  • 125
  • 1
  • 12

1 Answers1

6

There is no difference. In fact, there is no difference between the two syntaxes in JavaScript as a whole:

someObj.someProp === somObj["someProp"];

The only difference is that certain characters are valid in a string and not in a dot-property name:

someObj["some-prop"] // valid
someObj.some-prop // this is actually the value of `someObj.some` minus the value of `prop`

Note that both of these methods of storing values in localStorage are also the same as using the .getItem and .setItem methods. According to the W3C spec:

Each Storage object provides access to a list of key/value pairs, which are sometimes called items.

These items are accessible and mutable via the object property of the same name or by refering to them by name using .getItem and .setItem. The only difference is that the functions can be overwritten to provide wrappering, e.g., to JSON-ify the object before storage:

localStorage.setItem = function(key, val) {
    localStorage[key] = JSON.stringify(val);
}
ChrisN
  • 16,635
  • 9
  • 57
  • 81
apsillers
  • 112,806
  • 17
  • 235
  • 239
  • 5
    `someObj.someProp === somObj["someProp"];` Not true, if the value is `NaN`. TROLOLOLO `:P` – Šime Vidas Aug 23 '12 at 23:25
  • 3
    @ŠimeVidas And neither true when using `var someObj={};Object.defineProperty(someObj,'someProp',{get:function(){return{};}});`. `NaN` is more likely to occur than this one, though ;) – Rob W Aug 24 '12 at 08:41
  • 1
    @ŠimeVidas And while we're being entirely precise, the dot and bracket notations on `localStorage` differ slightly from `set`/`getItem`: property access cannot persistently store values in keys that share the name of native properties on `localStorage`, whereas function access can. The line `localStorage.setItem = "foo"` does not cause persistent storage, whereas `localStorage.setItem("setItem", "foo")` does. `:P` – apsillers Aug 24 '12 at 13:02