JavaScript For Cats

Objects

Arrays are good for lists, but for other tasks they can be hard to work with. Consider our array of cat friends. What if you also wanted to store more than just names?

var myCatFriends = ["bill", "tabby", "ceiling"]
var lastNames = ["the cat", "cat", "cat"]
var addresses = ["The Alley", "Grandmas House", "Attic"]

Sometimes it is nice to have all of the addresses or names in one variable. But sometimes you have a cat in mind, let's say Bill, and you just want to look up that cat's address. With arrays it takes a lot of work because you can't just say 'hey array, give me Bill's address' because 'Bill' is in one array and his address is in a totally different array.

Console

This can be brittle because if our arrays change and we add a new cat to the beginning we would have to also update our billsPosition variable to point to the new location of Bill's information in the arrays! Here is an easier to maintain way to store information like this using objects:

var firstCat = { name: "bill", lastName: "the cat", address: "The Alley" }
var secondCat = { name: "tabby", lastName: "cat", address: "Grandmas House" }
var thirdCat = { name: "ceiling", lastName: "cat", address: "Attic" }

Why would we do it this way? Because now we have a variable for each cat that we can use to get that cats values in a more convenient and readable way.

Console

You can think of Objects like keys on a keyring. Each one is for a specific door and if you have nice labels on your keys you can open doors very fast. In fact, the things on the left hand side of the : are called keys (are also known as properties) and the things on the right hand side are values.

// an object with a single key 'name' and single value 'bill'
{ name: 'bill' }

So why would you ever use arrays if you can just put your data in objects? Because objects don't remember the order of the keys that you set. You might enter in an object like this:

{ date: "10/20/2012", diary: "slept a bit today", name: "Charles" }

But the computer could give it back to you like this:

{ diary: "slept a bit today", name: "Charles", date: "10/20/2012" }

Or like this!

{ name: "Charles", diary: "slept a bit today", date: "10/20/2012" }

So you can't ever trust the order of keys in objects. If you wanna get REALLY fancy you can make an array filled with objects, or an object filled with arrays!

var moodLog = [
  {
    date: "10/20/2012",
    mood: "catnipped"
  },
  {
    date: "10/21/2012",
    mood: "nonplussed"
  },
  {
    date: "10/22/2012",
    mood: "purring"
  }
]

// ordered from least to most favourite
var favorites = {
  treats: ["bird sighting", "belly rub", "catnip"],
  napSpots: ["couch", "planter box", "human face"]
}

When you combine different things like this you are making data structures, just like legos!