JavaScript Objects

Objects are made up of key:value pairs. Keys are always strings whether you put them in quotes or not. If in quotes then you may have spaces in the name, otherwise they may not have spaces.

To make an object, you var object {}; . You can put items into the object in two ways:

individually, var cat {}; cat[“name”] = “Jack”; cat[“legs”] = 5; cat[“color”] = “purple”;

or  through dot notation, such as cat.name = “Jack”;.

Another way is at the time of creation: var cat = {“name”: ”Jack”, ”legs”: 5, ”color”: ”purple”};.

Browsers may output keys in different order than setup or from one another. Dot notation is only for objects and not arrays.

If you are trying to get 123 out of some array, you can’t with dot notation because of the space in some array name. If the property name has a space, hyphen or begins with a number, you must use brackets.

var myCrazyObject = {

 “name”: “A ridiculous object”,

 “some array”: [7, 9, { purpose: “confusion”, number: 123 }, 3.3],

 “random animal”: “Banana Shark”

};

You can get the value ‘A ridiculous object’ from name with myCrazyObject.name; or myCrazyObject[“name”];

You can’t get to some array with dot notation because of space in string, instead you will get VM5869:2 Uncaught SyntaxError: Unexpected identifier message. You must instead use the bracket notation with myCrazyObject[“some array”]; . To get to the 123 inside some array you would do this…

myCrazyObject[“some array”][2].number; or myCrazyObject[“some array”][2][number]; to get

123.

More learning to come. Stay tuned.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s