Javascript Object Literals


This tutorial covers the following:

  1. Review of Arrays
  2. 2D Arrays
  3. Objects literals
  4. Objects literals with methods

These examples are taken from Allison Parrish.

1. A Review of Arrays.

Adding items to an array

Remember arrays in javascript (unlike in Processing) can change length. Therefore we can add to them when our code is running.

push() adds an item to the array. In the following example, we use this method to add a falling rectangle to the sketch whenever the user clicks:


 

3. 2D Arrays, Keeping track of multiple properties

But how would you make a sketch so that when you click the screen, a rectangle appears at the coordinates of the mouse click and then moves downward from there.

For this, we’ll need to keep track of two values for each rectangle. This is a bit tricky, and there’s more than one way to do it, each with their own benefits and drawbacks. We’re going to implement two options.

Arrays inside arrays

One solution relies on the fact that arrays themselves are values, and so we can store an array inside another array. To demonstrate, type the following into an empty sketch and example the debug output:

var stuff = [];
stuff.push([24, 25]);
stuff.push([26, 27]);
console.log(stuff); // displays [[24,25],[26,27]]

After you run this code, the variable stuff is an array which has two elements, both of which are themselves arrays. If you get the value at index zero, you get an array:

console.log(stuff[0]); // displays [24,25]

To get one of the two values from that array, you need to take the expression that evaluates to the outer array and use the square bracket syntax on that expression to get the inner value out, like so:

console.log(stuff[0][1]); // displays 25

We can use this idiom to create a version of our falling rectangle sketch that has just one array to store information about all rectangles. Each element of that array is itself an array.


The beauty of this is that we can easily add a third attribute to each rectangle simply by adding a third element to the array that we add to the rectXY array on each click. In the following example, a random value is stored in index 2 on each click, and then this number is used to give each rectangle a random color in draw():


EXERCISE: Try adding a fourth element to the array that controls how fast the rectangle falls.

3. Object Literals: Rectangles as Objects

Here’s a version of our rectangle sketch that puts it all together. On each click, this sketch creates a new object and pushes it into the rectObjs array. This is another syntax for a Javascript object called an object literal.

In draw(), each rectangle is displayed by accessing the values using the appropriate keys:


EXERCISE: Modify the above example so that each rectangle object also stores a separate speed for the X and Y coordinates, then modify the draw() loop so that the rectangles move in directions other than downwards.

Objects Literals with Methods

A method is just a function that is the value for a key in an object. For example, try running this code in an empty p5.js sketch:

var rectangle = {
    width: 100,
    height: 200,
    area: function() {
        return this.width * this.height;
    },
    perimeter: function() {
        return 2*this.width + 2*this.height;
    }
};
console.log(rectangle.area()); // 20000
console.log(rectangle.perimeter()); // 600

This code creates an object named rectangle, which has four attributes: the values for width and height are both numbers, and the values for area and perimeter are both function values. Because these functions are values in an object, we call them methods.

There are two bits of syntax you need to know to get started using methods. The first is how to call a method. To do this, take an expression that evaluates to an object, follow it by a dot (.), and then type the name of the method, followed by parentheses. (Methods can also take parameters, in which case the parentheses won’t be empty. See below.)

The second bit of new syntax is this. Inside of the method, there’s a special keyword this which refers to the object that contains the method. You can access properties, overwrite properties, add new properties, and even call methods of the containing object.

Here’s a version of the example from above. This time, however, the mousePressed()function adds objects to the array that have methods of their own for display() and update().


EXERCISE: Modify the above example so that each rectangle object includes speed variables in the X and Y directions. Modify the methods to also include this.