Cloudboy22
Cloudboy22

Reputation: 1514

adding an array to Local Storage

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.

Upvotes: 0

Views: 152

Answers (2)

Vontei
Vontei

Reputation: 1897

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.

Upvotes: 2

ChadF
ChadF

Reputation: 1758

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')
}

Upvotes: 2

Related Questions