JavaScript Objects

This tutorial is part of a web programming course for people who have no programming experience.


You've already learned about variables, and how they store different types of data. We discussed numbers, strings, and boolean data types. Another data type that a variable can store in JavaScript is called an object and it's extremely useful.

When writing programs, you often need to keep track of information regarding real world objects. For example assume that you are creating a program that keeps track of dogs (maybe you got hired to build a website for the Humane Society). You could create 'dog' objects in your code, and each one would represent a real dog. A dog object should contain all the relevant information about the real dog that it represents. If your program requires that you keep track of a dog's name, breed, and whether it has been vaccinated, then each dog object that you create in your code should store that information. These are the properties of each dog that you need to track in your program.

An Object is a Collection of Properties

An object is a collection of properties (and their values). Actually, there's more to it than that, and we'll get to it later, but for now I want you to understand that an object is made up of properties. This is how you could create a dog object in your JavaScript code:

var myDog = { name: "Buster",  breed: "mut",  age: 3,  vaccinated: true };

The variable myDog stores an object that has four properties. The names of these properties are name, breed, age, and vaccinated. Each one of these properties has been assigned a value. Note that the data type of each value may differ, the 'name' and 'breed' properties are storing string values. The 'age' property is storing a number, the 'vaccinated' property is storing a boolean.

Each property and it's assigned value can be thought of as a name/value pair.

Before moving on, I'd like to point out that until now, all the variables we have used in this course have stored a single value. When a variable stores an object data type, it is actually storing a little bundle of related values. And each of these values helps to describe the object that we are simulating in our program.

Object Syntax

Here are the syntax rules for creating an object in your JavaScript code:

  • Use curly braces to enclose all the properties (all the name/value pairs) of an object.
  • Each property name is separated from its value by a colon.
  • Property name/value pairs are separated by commas (but notice that there is no comma after the last name/value pair)

You might see code in which each property name/value pair is written on its own line, which is common when an object has lots of properties:

var myDog = {
  name: "Buster", 
  breed: "mut", 
  age: 3,
  vaccinated: true
};

Pay close attention to the formatting in this example. The property name/value pairs are indented within the curly braces that enclose the object. Have I mentioned the importance of formatting your code properly yet in this course? The indentation helps programmers to visualize and read the code. If all the lines in the example above were aligned to the left then it would be hard to see that the property name/value pairs are nested within the object. And if a program has lots of lines of code that are all left aligned, then it would be hard to see where one object ends and another begins. Please make it a habit to format your code properly, you'll save yourself a lot of frustation by doing so. In my career as a teacher, I've seen that students who don't learn to format their code spend most of their time trying to figure out why they can't get relatively simple programs to work.

OK, I'm done ranting for now, let's move on...

Accessing the Properties of an Object

When your program has objects in it, you'll probably want to access their properties. For example, you may want to display, or console log, a specific property of an object. Continuing with our dog example, we could do so like this:

console.log(myDog.name);

To access the value of a property, you can use the dot operator to do so. The dot operator is simply a period that goes between the name of the variable that stores the object, and the name of the property within the object. The above code sample will display "Buster" in the console log.

You can also log the entire object like this:

console.log(myDog);

In this case all the properties (and their values) will be printed in the console log.

Updating Properties of an Object

You can change the value of a property in an object like this:

myDog.name = "Milo";

To change the value of a property, write the variable name followed by the name of the property, then assign a new value.

In many real world programs, user input is used to update properties of an object. In the example below, the prompt function is used to allow the user to change the name of our dog object:

myDog.name = prompt("Enter a new name for the dog");
console.log(myDog);

The prompt function is useful when your are learning and experimenting, but it's not practical for most real world programs. In an upcoming lesson we'll build an HTML form to allow users to enter input.

Adding Properties to an Object

Unlike some other programming languages, JavaScript allows you to to create an empty object and then add properties to it as your program executes. Take a look at this example:

var yourDog = {};
yourDog.name = prompt("What is your dog's name?");
yourDog.breed = prompt("What breed is your dog?");
yourDog.age = parseInt(prompt("How many years old is your dog?"));
var isVaccinated = prompt("Has your dog been vaccinated (yes/no)");

if(isVaccinated == "yes"){
	yourDog.vaccinated = true;	
}else{
	yourDog.vaccinated = false;
}

The first statement in this code sample declares a variable (yourName) and assigns to it an empty object (an object with no properties). In the following statements properties are added and assigned values by prompting the user for input. Remember that in JavaScript all user input is presumed to be a string data type, so we have to jump through a few hoops to set the 'age' and 'vaccinated' properties.

There is an alternative syntax for working with properties of objects, and we'll explore it in the next. The examples above are using dot notation to add and update properties of an object.

Bracket Notation

While dot notation is by far the most commonly used syntax when working with objects in JavaScript, there is another approach that you may see called bracket notation.

myDog['age'] = 10;
console.log( myDog['age'] );

To access a property using bracket notation, you start by writing the variable name, and add a pair of square brackets ([]). Inside the square brackets you write the name of the property BUT you must put quotes around the property name. You can use either single or double quotes but it must be the same for each side (you could not put a single quote before the property name, and a double quote after it). Beginning students will often forget to put the quotes around the property names when using bracket notation, which will most likely cause the program to crash. But the quotes are important, because bracket notation allows you to do something that you can't do with dot notation. The code that goes in between the square brackets can be an expression. Consider this code sample:

var propertyName = prompt("Which property of myDog would you like to look up?");
console.log( myDog[propertyName] );

Remember that a variable, such as propertyName in this case, is an expression that will be evaluated when your program executes. When we write this code, we don't know what value will be stored in the propertyName variable, because it depends on what the user enters when the program runs in the browser. It's entirely possible that the user will enter something invalid (something that is not the name of a property in the dog object). You should never trust that a user will enter valid input, and your code should always check for this. We can 'bullet proof' our program a little bit by adding this IF statement:

if(myDog[propertyName]){
	console.log(myDog[propertyName]);
}else{
	console.log(propertyName + " is not a property in the dog object");
}

If the value stored by propertyName is not the name of a property in our dog object, then myDog[propertyName] will evaluate to undefined, which is false (recall our discussion of 'falsy' values). You should always take every step possible to 'bullet-proof' your program by considering everything that could possibly go wrong, and then adding code to handle each situation. This is called defensive programming and we haven't been doing much of it because we are focusing on other fundamentals. But as you gain more experience, and move toward building real world applications you will have to account for everything that could possibly go wrong. You have to assume that anything that CAN go wrong WILL.

Summary

Objects are a critical part of many programming languages. They allow us to make models that simulate the properties of real-world objects in our programs. We'll soon find out that objects can do much more as well.

NEXT LESSON: JavaScript Methods