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.

2

2 Answers 2

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')
}
Sign up to request clarification or add additional context in comments.

1 Comment

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").
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.