Object Basics

Celeste Layne
Programming for Design Practices
5 min readJun 25, 2020

--

Josef Albers

Intro to Objects

The focus of this lesson is objects, an exciting aspect of JavaScript that ties into many of the concepts you’ve already learned. Once you get to know objects, you’ll realize how much easier your coding life can be.

Easier access to data

Let’s say we are developing a website for an art gallery. Using a regular array, we would store each gallery’s information:

let artist = ["Frida", "Kahlo", "Surrealism", 1907, "Mexico"];

There are only a handful of values in this array, but there is no context for any of them. Is “Mexico” where she was born or where she lived most of her life? It’s difficult to tell because we have no clear reference for each data point.

Take a look at how we could represent this artist with an object. Don’t worry about syntax for now; we’ll cover that soon. Just use the following example to get a feel for how to associate keys with values.

let artist = {
firstName: "Frida",
lastName: "Kahlo",
yearOfBirth: 1907,
countryOfBirth: "Mexico"
};

By associating keys with values, we can more accurately represent our artist object. Now we know at a glance what “Mexico” is referring to — our artist’s country of birth.

What are objects good for?

Objects serve two main purposes in JavaScript:

  1. They act as a simple, structured data store. And, while they are similar to arrays, they access values using keys instead of indices.
  2. They provide a fundamental programming paradigm that helps us structure and categorize code — known as Object Oriented Programming.

In JavaScript, every physical thing can be represented as an object.

Properties and Methods

Each object can also have its own properties and methods.

Properties

Properties are characteristics associated with an object. If a function is part of an object, it becomes a method. If a variable is part of an object, it becomes a property. In other words, properties tell us about an object.

let animal = {
name: 'Pilot', <-- this is a property
species: 'dog',
breed: 'Newfoundland',
makeNoise: function() { <-- this is a method
console.log('bark!');
}
};

Methods are used to represent how people interact with an object in the real world. In other words, methods are the actions that can be performed on objects.

We can use methods to:

  1. Retrieve the values of an object’s properties to find out something about that object.
  2. Update the values of an object’s properties.

Creating Objects

Let’s explore how we can add properties and methods when creating objects.

Object Literal Notation

Let’s say we want to create objects for several popular artists, starting with Frida Kahlo. We might want to add some properties for Frida Kahlo: a first name, last name, and year of birth.

We might also want to add a method to our Artist object which will return her first and last name (Frida and Kahlo), followed by her country of birth(Mexico).

Here’s how we would write this object using literal notation:

let artist = {
// Properties
firstName: "Frida",
lastName: "Kahlo",
countryOfBirth: "Mexico",

// Methods
printShortBio: function() {
return this.firstName + " " + this.lastName + " was born in" + this.countryOfBirth;
}
};

Let’s look at the syntax breakdown:

  • Our object is contained within curly braces { }.
  • We are storing our object in a variable, called artist.
  • We separate each key from its value using a :.
  • To add a property, we use a property name, such as firstName, lastName, or countryOfBirth, followed by a :, followed by the corresponding value: 'Frida', 'Kahlo', or 'Mexico'.
  • To add a method, we would use the method name printShortBio, followed by a :, followed by an anonymous function (function (){}).

This — A brief Overview

In the context of our objects, this is used in place of the object name to refer to the current object instance. In a method, this refers to the object containing the function. For example, in the function below, this refers to the animal object that contains the method makeNoise.

let animal = {
name: 'Pilot',
species: 'dog',
breed: 'Newfoundland',
noise: 'bark!',
makeNoise: function() {
console.log(this.noise); <-- this refers to the object, animal
}
};

Because this refers to the animal object, using it would be the same as writing out:

console.log(animal.noise);

Dot Notation

Dot notation is common for simple scenarios. We can access values using the object name, followed by a period ., followed by the name of the property we want to access.

Here, we’ve created the variables artistFirstName and artistLastName to store the information we want to retrieve.

// Store 'Frida' in the artistFirstName variable.
let artistFirstName = artist.firstName;

// Store 'Kahlo' in the artistLastName variable.
let artistLastName = artist.lastName;

Updating Properties Using Dot Notation

To update values using dot notation, use the name of the object (in this case, artist), followed by the name of the property we want to update (in this case, .firstName or .lastName). Then use the assignment operator (=) followed by the new value.

artist.firstName = 'Magdalena Carmen Frida';

Adding New Properties

The syntax we use to update a property can also add a new one. If the property we are trying to update doesn’t yet exist, it will be added automatically.

artist.spouse = 'Diego Rivera';

Square BracketNotation

To access values, we can also use square bracket syntax to access and update the properties for an object.

// Store 'Frida' in the artistFirstName variable.
let artistFirstName = artist['firstName'];

// Store 'Kahlo' in the artistLastName variable.
let artistLastName = artist['lastName'];

Once again, the name of our object is artist, followed by the property name, contained within quotes and square brackets. The square bracket syntax is commonly used when a variable name is used in place of a property name:

let propertyName = 'firstName';
let artistFirst = artist[propertyName]; => 'Frida'

Accessing Methods

We will use dot notation to access methods for our objects. If we wanted to access — or call, our makeNoise method — we could do so using the following syntax:

let noise = animal.makeNoise();
=> 'bark!'
  1. Here, we use the object name animal, followed by a period, followed by the method name, followed by parenthesis.
  2. We are saving the value that is returned in a variable, noise, so we can reference it later.

Iterating Through an Object

Like arrays, you can use a loop to iterate through an object. Let’s say we want to print out all of an object’s keys, we can use a for...in loop:

for (item in items) {
console.log( item );
}

--

--