Javascript: Objects

Basic Syntax

Objects are similar to arrays in the sense that they store data. However Objects use key value pairs and are better suited for many types of data. Here is a sample of a simple object:

var person = {
name: "Nick Coughlin",
hair: "blond",
city: "Eugene"

A key difference between objects and arrays, is that items in objects have no order. The data must be retrieved by using the key.

Retrieving Data

//bracket notation

//dot notation

So why would anyone ever use the bracket notation when dot notation is so much simpler. Well there are some notable exceptions where dot notation will not work.

// you cannot use dot notation if the property starts with a number
someObject.1anything   //invalid
someObjet["1anything"] //valid

// you cannot use dot notation for property names with spaces
someObject.fav restaurant    //invalid
someObject["fav restaurant"]   //valid

// you cannot lookup a variable with dot notation
var str = "name";
someObject.str    //does not look for "name"
someObject[str]   //does evaluate str and look for "name"

Updating Object Data

This is very similar to updating array data. For objects you simply access a property and then reassign it.

var dog = {
name: = "lola",
age: = 5,
weight = 40

// to update the age
dog["age"] += 1;
// to update weight
dog.weight = 50;  //jesus lola, slow it down