Mon, Sep 26, 2016


Objects are variables that can store associative data and functions. Objects have a much larger role in JavaScript than just storing data, as we’ll find out later. But at this point in the tutorial we’ll learn about how to create a basic generic object— in our case mostly used for storing associative data.

There are three basic formats for writing objects:

  • Object literal
  • Dot notation
  • Square bracket notation

Object Literals

An object literal is a method of writing an object. You cannot recall values from an object using a literal, only assign values.

An object literal is written with curly braces. Each item in the object contains an keyword called a property and it is separated by a colon with the value of that property.

var person = {name: "Jim", age: 47, location: "Berkeley"};

In the above example, we’ve created a variable called person, and we’ve associated three properties with this person; a name, age and location. Each property is assigned a value, with an according datatype.

Using Dot Notation To Create Objects

It is possible to create a generic object without assigning it a value. This is called instantiating, a process that will become more important later when we cover classes.

var dog = new Object();

Once we’ve instantiated an object, we can assign properties to it.

dog.name = "Rex";
dog.type = "hound";
dog.age = 3;
dog.hasFleas = false;

It is important to note that this is another way of creating and assigning values to an object. We could achieve the same exact result with an object literal like so:

var dog = {name: "Rex", type: "hound", age: 3, hasFleas:false };

Using Square Bracket Notation to Create Objects

Square bracket notation is very similar to dot notation, and it offers a few advantages. The primary advantage is that property names can have spaces, since they are strings. This also allows us to calculate property names dynamically.

Like dot notation, we must first instantiate an object:

var cat = new Object();

Next, we assign properties to it.

cat["name"] = "Penny";
cat["type"] = "Tabby";
cat["age"] = 3;
cat["likes to sleep"] = true;

Take note of the last line of the above code. The property “likes to sleep” has spaces, so typing this as dot notation would not be possible.

Just as with dot notation, we can create this object using object literals. Below is the identical method of creating the cat variable using object literals:

var cat = {name : "Penny", type : "Tabby", age : 3, "likes to sleep": true };

Surrounding property names in quotes is usually optional in object literals, but it is required when property names have spaces.

Arrays and Objects

Arrays and objects work well together. They are very similar, but have some important differences. Objects use properties to identify values, while Arrays use an index number, to store multiple values.

In this following example, we have an array of office workers. Each item in the array is a different object that we can reference.

var officeWorkers = [ 
    {name: "Suzy",   position: "secretary", "years of employment": 5},
    {name: "Jim",    position: "manager",   "years of employment": 2},
    {name: "Robert", position: "janitor",   "years of employment": 10},
    {name: "Mary",   position: "CEO",       "years of employment": 1}

In the above array, if we wanted to reference any of the objects, we would first use the index of that object, then use the respective property name. For example, if we wanted to get Mary’s position we would reference that by one of two ways:


Either dot notation or square bracket notation can be used to recall information. Remember, object literals are only for assigning data, so we cannot use them to retrieve values from an object. Advantages of using square bracket notation

Square bracket notation has benefits because we can dynamically create the property name. There are situations where we may wish to reference a property of an object in response to a particular action by the user, or for retrieving data from a very large dataset. Consider the following example:

var photos = {
    photo1: "fish.jpg",
    photo2: "cat.jpg",
    photo3: "dog.jpg",
    photo4: "horse.jpg",
    photo5: "turtle.jpg",

While we can retrieve any of these items using the properties (photo1, photo2, photo3, etc.) sometimes we may need to specify the property name based on another value.

var currentPhoto = 1;
photos["photo" + currentPhoto];

In the above situation, the information in the square bracket will resolve to photo1, and thus retrieving the information for “cat.jpg” in the photos variable. The reason this happens, is because we’ve concatenated the string “photo” with the value 1 in the variable currentPhoto, which was set earlier. Objects inside of objects

Objects can be nested inside of other objects, and this is quite common practice. However, making the code legible is crucial to understanding the structure of the object. We generally use a mix of indentation and carriage returns (new lines) to make the code human-readable.

var blogData = {
    title : "Headline for my blog post",
    author : "Jeremy Rue",
    meta : {
        date : "Jan 1, 2012",
        time : "12:00am",
        keywords : "blog post berkeley"

In this above example, you can see that the value of the meta property is another object. Using both dot notation or square bracket notation, we could recall these values—such as the keywords property—like so:


JavaScript Object Notation, or JSON

There is a standard on the web for transferring information between websites called JavaScript Object Notation, or JSON (pronounced “jase-on.”) JSON is simply a combination of JavaScript object notation and arrays. JSON is used by many other programming languages than JavaScript, and has cemented itself as a standard format for data. This is why understanding objects, arrays and datatypes is so crucial for understanding how JavaScript works.

Here is an example of some JSON formatted data:

    "firstName": "Ross",
    "lastName": "Marshall",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    "phoneNumber": [
            "type": "home",
            "number": "212 555-1234"
            "type": "fax",
            "number": "646 555-4567"

It’s important to know that JSON is just referring to the data part. When you have a .json file, it shouldn’t be assigned to a variable.


Sometimes JSON will be transferred in a way where it’s automatically encased in a function call, known as JSONP. This is often done to get around browser security limitations called CORS (Cross-Origin Requests).

Such an scenario might look like this:

    "firstName": "Ross",
    "lastName": "Marshall",
    "age": 25

In the case above, this file isn’t actually JSON. It’s a JavaScript that is wrapping the JSON code in something called a function that we will learn about in the next lesson. In order to receive or transfer the above code from a website with a different domain, we would need to also create the function to receive that JSON.

var myJSON;

function callback(data){
    myJSON = data;

This is a bit advanced and won’t make a lot of sense until we cover functions in the next class. It’s important to introduce the topic, however.