JavaScript Objects
Literal Notation and Function Constructors
There are different ways to create objects in JavaScript. In this article, we will focus on creating objects using literal notation and function constructors.
Terminology
Before going into how to create objects, let’s take a look at some terms that are used when talking about objects. Objects are written inside curly braces, as in the example shown below. The object in this example is stored in a variable called person1
, and can be referred to as the person1 object. Properties tell us about the object. Here, the properties are name
and DOB
(date of birth). If a function is part of an object, it is called a method- an action that can be performed on an object.
In this example, the method is age
, which calculates a person’s age. Just like variables and functions that are named, properties and methods in objects have a name and a value. When we talk about objects, these are called keys and values. In this example, the keys are name
, DOB
, and age
. Their corresponding values are Jim
, 1997
, and the function that calculates age. Values can be strings, numbers, Booleans, arrays, or even another object.
Literal Notation
We have just seen our first object example: the person1 object. This is also an example of an object created using literal notation. In an object literal, you begin by defining the variable name for the object (in this case person1
), the actual object is the curly braces and the content inside the curly braces. A colon is used to separate each key from its value, and each property and method is separated with a comma (except for after the last value). As mentioned above, values can be strings, numbers, Booleans, arrays, or even another object. When we set our properties, the values are treated the same way that variables are treated. So here, since Jim
is a string, we use quotation marks, and (since 1997
is a number) no quotation marks are used. If this object had a Boolean property of isMarried
, then its value would either be true
, indicating that Jim is married, or false
, indicating that Jim is not married.
var person1 = {
name: 'Jim',
DOB: 1997,
age: function() {
return 2020 - this.DOB;
}
}
Accessing the Object
To access the object, we simply use the name of the object (i.e. the variable name). In this case, we simply do console.log(person1)
. Doing so will allow us to access the entire object.
var person1 = {
name: 'Jim',
DOB: 1997,
age: function() {
return 2020 - this.DOB;
}
}console.log(person1);
When this is logged to the console, we get our person1 object:
{name: "Jim", DOB: 1997, age: function}
Let’s say that we don’t want to access the entire object. To access individual properties or methods of an object we use what is called dot notation. To do this, we simply use the name of the object (in this case, person1
), followed by a period, then the name of the property or method that we want to access objectName.propertyName
. For example, if we want to access the name of our person1 object, we would simply do person1.name
. In the following example, we are accessing the name (person1
) and the age method (person1.age()
), which calculates the person’s age, and logging it in to the console in a string:
var person1 = {
name: 'Jim',
DOB: 1997,
age: function() {
return 2020 - this.DOB;
}
}console.log("Hello, I'm " + person1.name + " and I'm " + person1.age() + " years old.");
So now in the console, we get the following. As you can see, the name has been accessed, as well as the age, which has been calculated using the age method:
Hello, I'm Jim and I'm 23 years old.
We can also access the properties or method of an object using bracket notation: objectName['properyName']
. With this syntax, the object name is followed by square brackets, with the property or method in quotation marks inside the square brackets:
console.log(person1['name']);
console.log(person1['age']());
console.log(person1['name'] + ' is ' + person1['age']() + ' years old.');
And so when this is logged to the console, we get the following:
Jim
23
Jim is 23 years old.
Function Constructors
Another way of creating objects is by using function constructors. There are times when you may want to create multiple objects with the same properties (e.g. contacts and their contact information). With function constructors, you can create a blueprint for creating objects. Let’s say, for example, that we have the following object literal:
var contact = {
name: 'John Doe',
email: 'jdoe@test.com',
DOB: 1985,
age: function () {
return 2020 - this.DOB;
}
}
Then, let’s say that we want to create an app that allows users to add and store their contacts, along with their contact information. We can assume that a user will be adding a large number of contacts. In this case, it would be better to create some sort of blueprint rather than to go through the process of creating object literals for every single contact. This is where function constructors come in.
To do this, we create a function called Contact which will be used as the blueprint for creating new objects that represent a user’s contacts (the name of the function begins with a capital letter by convention). In this case, the function has four parameters (name, email, DOB, and siblings). Each of these parameters sets the value of a property in the object. As for the method (age), it is the same for each object created using this function. As before, the actual object is the curly braces and the content inside the curly braces. Notice too that each of the statements inside the object ends in a semicolon and not a comma (which is used in literal notation).
What’s different here is the use of the this
keyword. When used in an object, the value of this
is the object itself. It represents the object being created. So rather than using a key like name
(as we did in the object literal example above) we use this
to show that the property or method belongs to the object. In other words, by using this.name
, for example, we are saying that name
belongs to the object Contact.
function Contact(name, email, DOB, siblings) {
this.name = name;
this.email = email;
this.DOB = DOB;
this.siblings = siblings;
this.age = function (DOB) {
return 2020 - this.DOB;
}
}
Now that we have our Contact blueprint, we can create instances of this object. In our example, this means creating specific contacts. To do this, we use the new
keyword and then call the function that we defined above (Contact). We then pass in the arguments. Remember that when we created our Contact blueprint, we had four parameters (name, email, DOB, and siblings). So now when we call the function, we pass in our four corresponding arguments. In the example below, the arguments for john
are "John Doe", "jdoe@test.com", 1985
and the array, ["Tom", "Anne"]
. We then save this in a variable called john
. As for the age
method, remember that each instance will get the same method as defined above. And each time we create a new instance, the arguments that are passed in are different, since each instance represents a specific contact. Notice how the arguments that are passed in for carol
are unique to her, just as the arguments that are passed in for john
are unique to him.
So now we’ve created two new contacts, each with just about one line of code. The benefit of using function constructors to create objects is now apparent. If we were to have a total of 10 contacts (instances), we would only need about 10 lines of code (one per contact), compared to how many more lines of code we would need to write if we were to create each contact using literal notation.
var john = new Contact("John Doe", "jdoe@test.com", 1985, ["Tom", "Anne"]);
var carol = new Contact("Carol Lee", "carol@jmail.com", 1965, ["David", "Mary", "Rose"]);
Accessing the Instances
To access each instance, we simply use the name of the instance that we created, in our case, john
and carol
: console.log(john)
and console.log(carol)
.
var john = new Contact("John Doe", "jdoe@test.com", 1985, ["Tom", "Anne"]);
var carol = new Contact("Carol Lee", "carol@jmail.com", 1965, ["David", "Mary", "Rose"]);console.log(john);
console.log(carol);
As with our object literal example above, simply using the name will allow us to access the entire object. And when we check the console, this is indeed the case. And so we get our two contacts:
Contact {
name: 'John Doe',
email: 'jdoe@test.com',
DOB: 1985,
siblings: [ 'Tom', 'Anne' ],
age: [Function]
}
Contact {
name: 'Carol Lee',
email: 'carol@jmail.com',
DOB: 1965,
siblings: [ 'David', 'Mary', 'Rose' ],
age: [Function]
}
To access the properties or methods of our instances we use dot notation (just like we did when using literal notation) using the names of our created instances (john
and carol
), followed by a period, then the name of the property or method that we want to access. We can log our two contacts and their information to the console, using \n
for line breaks, and even adding a divider between the two contacts so that the result is easier to read:
console.log("Name: " + john.name + "\n" + "Email: " + john.email + "\n" + "Siblings: " + john.siblings + "\n" + "Age: " + john.age());console.log('\n*******************************\n');console.log("Name: " + carol.name + "\n" + "Email: " + carol.email + "\n" + "Siblings: " + carol.siblings + "\n" + "Age: " + carol.age());
The result in the console looks like the following example. Now we get the contact information for John and Carol with line breaks after each property as well as a divider that’s been added between the two contacts.
Name: John Doe
Email: jdoe@test.com
Siblings: Tom,Anne
Age: 35*******************************Name: Carol Lee
Email: carol@jmail.com
Siblings: David,Mary,Rose
Age: 55
Summary
This article looked at two different ways of creating objects in JavaScript. After defining the terminology that is used when talking about objects, we looked at how to create objects using literal notation, as well as how to access an entire object, and its individual properties and methods. The next section discussed how to create objects using function constructors, as well as how to access instances of an object, and their individual properties and methods. While objects created using literal notation is the simplest way of creating an object, function constructors come in handy when creating multiple objects with the same properties.