0

i am a newbie to HTML5. I am reading head first HTML5 programming. Here in a chapter it's mentioned that We are grabbing the array out of localStorage.

function init() {
    // button code here...
    var stickiesArray = localStorage["stickiesArray"];
    if (!stickiesArray) {
        stickiesArray = [];
        localStorage.setItem("stickiesArray", stickiesArray);
    }
    for (var i = 0; i < stickiesArray.length; i++) {
        var key = stickiesArray[i];
        var value = localStorage[key];
        addStickyToDOM(value);
    }
}

I didn't understand this line var stickiesArray = localStorage["stickiesArray"];

We are grabbing StickiesArray out of Localstorage. But should not there be a dot between them like var stickiesArray = localStorage.stickiesArray; to grab the items from localstorage?? Thanks.

Pavan Ravipati
  • 1,890
  • 14
  • 21
Cloudboy22
  • 1,496
  • 5
  • 21
  • 39

2 Answers2

2

There are two ways to access a property in an object, dot and bracket notation.

Dot Notation: myObject.property

Bracket Notation: myObject["property"]

At runtime dot notation is actually converted to bracket notation, it's just a shorthand for us programmers. This means that anything using dot notation is going to be converted to a string. So if you're in a for-in loop like so:

for(var key in object) {
  // object.key -> object["key"] (This will be undefined)
  object[key] // (looks up the variable 'key')
}
ChadF
  • 1,750
  • 10
  • 22
  • It's worth pointing out that the bracket notation is the only way to access a property where the name is contained in a variable (e.g., `myObject[prop]` is the value in `myObject` of the property name currently stored in `prop`). Of course, for `localStorage` there's yet another way: `localStorage.getItem("property")`. – Ted Hopp Jun 17 '15 at 02:27
2

In javascript, when you have object literal notation...aka declaring objects outright, and/or declaring key/value pairs, you have two choices:

Object.name = "FOO"; or Object['name'] = "FOO";

dot notation may often be preferred for ease of use, but brackets have a larger scope in that they can ALWAYS be used. There are instances in object literals where dot notation is not allowed.

var stickiesArray = localStorage["stickiesArray"] sets the variable stickiesArray equal to an object that has a property/value of local storage: stickiesArray.

Vontei
  • 1,727
  • 2
  • 14
  • 16