Objects
This lesson is part of the Web Programming 1 Course.
In this lesson we are going to take a giant leap in your journey to learn programming! We are going to discuss object-oriented programming, and you may spend many more years learning the intricacies of this approach that has been the main paradigm used in building software applications for many years.
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 about 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 that is tracked by your application. A dog object in your program 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. This is how you could create a dog object in your JavaScript code:
const 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. The value of the name property is 'Buster', the value of the age property is 3, and so on. So object properties consist of a property name and a property value and together they are known as a name/value pair
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.
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, like so:
var myDog = {
name: "Buster",
breed: "mut",
age: 3,
vaccinated: true
};
This approach is commonly used when an object has many name/value pairs (because if you put them all on a single line, it would end up being very long).
Pay close attention to the formatting in the previous code example. The property name/value pairs are indented within the curly braces that enclose the object. This makes it easier to scan and read code (proper indention is so important in programming!).
Accessing the Properties of an Object
When your program has objects in it, you'll probably want to access their property values. For example, you may want to display, or console log, a specific property of an object. Continuing with our dog example, we could output the name of a dog like so:
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 whose value you wish to access. The above code sample will display "Buster" in the console log.
You can also log the entire object like this:
console.log(myDog);
If you check the console log after running code like this, you'll see that all of the object's name/value pairs will appear (although you click on the log entry to expand all the name/value pairs).
Object is a Data Type
We have already learned that variables store values, and that those values may be of various data types. You know that variables can store strings, numbers, and booleans. Objects are also a data type in JavaScript. To see this, use the typeof operator when logging a variable that stores an object:
console.log(typeof myDog);
As a side note, there are a few other data types in JavaScript that we have not yet discussed.
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 dot operator, then the name of the property, and finally use the assignment operator (the equals sign) to assign a new value.
Adding Properties to and 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:
const 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?"));
const 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 yourDog and assigns to it an empty object (an object with no properties - just curly braces with nothing between them). In the following statements, properties are added and assigned values by prompting the user for input. Remember that in JavaScript all user input defaults to a string data type, so we have to call the parseInt function to set the age property. We also need to jump through a hoop in order to set the vaccinated property.
Bracket Notation
There is an alternative syntax for working with properties of objects. The examples above are using dot notation to add and update properties, which means that we are using the dot operator.
While dot notation is by far the most commonly used syntax when working with objects in JavaScript, there is another approach that you should know called bracket notation. Here's an example:
myDog['age'] = 10;
console.log( myDog['age'] );
To access a property using bracket notation, you start by writing the variable name, then 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.
As mentioned, dot notation is by far more commonly used than bracket notation. But there are some things you can do with bracket notation that you can't do with dot notation. We don't need to worry about them at this point, we'll go over it in more detail later.
Virtual Objects
We can use object in programming to simulate things that do not physically exist. For example, a date, such as today's date is not a physical thing that you can touch and hold in your hand. To simulate a date in our program, the code might look like this:
const today = {
month: "October",
day: 22,
year: 2024
};
// let's log the properties of the 'today' object:
console.log(today.month);
console.log(today.day);
console.log(today.year);
I like to refer to these types of objects in programming as virtual objects. Can you think of any other 'virtual' objects that we might simulate in a program?
Complex Objects
In the real world, objects can be used to create other objects. Just think about all the objects that go into creating an automobile. I like to call objects that are composed of other objects complex. We can simulate complex objects in our by adding properties whose value is an object. Here is a very simplified object in JavaScript that could simulate a car:
const car = {
make: "Dodge",
model: "Journey",
engine:{
cylinders: 8,
horsePower: 250
}
}
Here you can see, that nested inside our car object is an engine. The engine is also an object (note the curly braces). The engine has two properties, cylinders and horsePower.
You can use dot notation or bracket notation to inspect the properties of the car and it's engine, like so:
// DOT NOTATION
console.log(car.make); // Journey
console.log(car.engine.cylinders); // 8
// BRACKET NOTATION
console.log(car['make']); // Journey
console.log(car['engine']['cylinders']); // 8
In one of the upcoming lessons, you'll see that when the browser loads a web page, it converts it into a highly complex object. And that we can use JavaScript code to manipulate the HTML on the page by working with this object.
Summary
Objects are a critical part of many programming languages. They allow us to make models in our code that simulate real-world objects. You can think of an object as a variable that stores a bundle of information that represents a real-world object.
In the next lesson, you'll learn that and object can be more than just a bundle of properties.