Introduction
JavaScript is a computer language that is used all over the world for programming purposes. There are various components that constitute the language. In this tutorial, we will be covering objects which are a data type. Objects are standalone entities that may comprise names, keys, or values. Each of these collections is represented in name:value pairs. These pairs may have methods and properties. Properties include any kind of data type, while methods are special functions in that object.
What are Objects?
It is very important to understand how objects work when you work with JavaScript. They play a very central role in the program and can be likened to objects in real life. For example, books could be considered objects which you would describe by the title, author, number of pages, and genre. Let’s say you have an object for the user account. This object may contain usernames, passwords, and email addresses. If your object is related to an eCommerce platform, it may contain the name, price, and weight of an item.
Now that you know what JavaScript objects are, we will learn how you can work with them. This tutorial will discuss what object properties and methods are. Then, we will show you how you can access the objects as well as perform a number of other functions.
How to Create a New Object?
First off, let’s see how you can make a new object. There are two ways to do so. The first is object literal where you use curly brackets {}. The second method is the object constructor where you use the new keyword.
As an example, we will show you how to make an empty object. We will first use the object literal:
1 2 |
// Initialize object literal with curly brackets const objectLiteral = {}; |
Next, we will use the object constructor:
1 2 |
// Initialize object constructor with new Object const objectConstructor = new Object(); |
Both methods will create an empty object. Next, we will describe a character. To do this, we will make an object within the variable called gimli:
1 2 3 4 5 6 7 8 9 |
// Initialize gimli object const gimli = { name: "Gimli", race: "dwarf", weapon: "axe", greet: function() { return `Hi, my name is ${this.name}!`; }, }; |
As you can see in the code above, we have our new object gimli. This object has three properties. Each property has a name:value pair that is called a key:value pair as well. One of the property names is weapon. This name is associated with the property value "axe". The latter is a string. Furthermore, this string has a method called greet with a value equal to the function contents. The greet method has this keyword using which helps you refer to the current object.
Let’s print out the whole object by sending it to the console:
1 |
gimli; |
1 2 |
Output: {name: "Gimli", race: "dwarf", weapon: "axe", greet: ƒ} |
What are Properties and Methods?
As we mentioned before, objects have properties and methods. A property is what links a name with a value. This means that it describes the characteristic of an object. It may contain any given data type. A method, on the other hand, is a function. This function is the value of an object property. Thus, think of the method as a task that the object can perform.
How Can You Access Object Properties?
You can access the object properties with either dot notation . or bracket notation []. Let’s demonstrate using our previous example:
1 2 3 4 5 6 7 8 |
const gimli = { name: "Gimli", race: "dwarf", weapon: "axe", greet: function() { return `Hi, my name is ${this.name}!`; }, }; |
Say you want to see the property value of weapon. To find this, you have to type the variable name of the object, then the dot notation ., and finally the property or method name:
1 2 |
// Retrieve the value of the weapon property gimli.weapon; |
1 2 |
Output: "axe" |
This gives you the property value which is "axe". Here is how you would do it using bracket notation:
1 2 |
// Retrieve the value of the weapon property gimli["weapon"]; |
1 2 |
Output: "axe" |
The property name is placed between two square brackets []. You can use either of these methods. You can also call an object method just like you would call a function:
1 |
gimli.greet(); |
1 2 |
Output: "Hi, my name is Gimli!" |
The output shows the string value of the greet() object method.
How to Add and Modify Properties?
Next, we will show you how to modify and add object properties. For this, you need to know about the assignment operator =. This helps you assign a new value to a property.
Continuing our previous example, we will add a number to the gimli object as the age property. You can use the dot or the bracket notation for this purpose:
1 2 |
// Add new age property to gimli gimli.age = 139; |
1 2 |
// Add new age property to gimli gimli["age"] = 139; |
You can access the value using either of the methods as well:
1 |
gimli.age; |
1 2 |
Output: 139 |
Similarly, you can also add methods to objects:
1 2 3 4 |
// Add new fight method to gimli gimli.fight = function() { return `Gimli attacks with an ${this.weapon}.`; } |
You can call the object and see the following output:
1 |
gimli.fight(); |
1 2 |
Output: "Gimli attacks with an axe." |
Now, we will see how to modify the object property. You can do this by assigning a new value to the already existing property:
1 2 |
// Update weapon from axe to battle axe gimli.weapon = "battle axe"; |
You will see the additions and modifications when you call the object at this point:
1 |
gimli; |
1 2 |
Output: {name: "Gimli", race: "dwarf", weapon: "battle axe", age: 139, greet: ƒ, fight: ƒ} |
How to Remove Properties?
We have a delete keyword for removing object properties. Let’s remove the weapon property from the gimli object:
1 2 |
// Remove weapon from gimli delete gimli.weapon; |
1 2 |
Output: true |
Your output will say true if the property is removed successfully. It will also give the same output if the property does not exist. You can also test this output:
1 |
gimli; |
1 2 |
Output: {name: "Gimli", race: "dwarf", age: 139, greet: ƒ, fight: ƒ} |
As you can see, the output does not have the associated value. This means you deleted the property successfully.
What is Looping?
Lastly, we will discuss how you can loop through object properties. This is for the purposes of iterating the properties of an object. You can use the built-in for...in loop for this. Here is an example:
1 2 3 4 5 |
const gimli = { name: "Gimli", race: "dwarf", weapon: "battle axe", }; |
Using the for...in loop you can see and print the properties of gimli on the console. You can acquire the property value as a variable using bracket notation:
1 2 3 4 |
// Iterate through properties of gimli for (let key in gimli) { console.log(gimli[key]); } |
1 2 3 4 |
Output: Gimli dwarf battle axe |
On the other hand, you can also retrieve the property name using the first variable in the for...in loop:
1 2 3 4 |
// Get keys and values of gimli properties for (let key in gimli) { console.log(key.toUpperCase() + ':', gimli[key]); } |
1 2 3 4 |
Output: NAME: Gimli RACE: dwarf WEAPON: battle axe |
Remember, the for...of loop is different from the for...in loop. The former is used for array type objects only. If you want to see an array of the object’s keys, use the Object.keys() method:
1 2 |
// Initialize method on gimli object to return property keys Object.keys(gimli); |
1 2 |
Output: ["name", "race", "weapon"] |
Using this method, you can work with the keys or names of the object in the form of an array.
Conclusion
This tutorial covered what JavaScript objects are in thorough detail. We talked about the properties and methods of objects. Then, we discussed how you can access, add, modify, and remove properties from objects. We used examples to make it easier to understand through demonstration. Now that you have an understanding of how objects work in JavaScript, you can go ahead with programming. These skills can be used to program useful features like shopping carts and user accounts.
Here are more resources from our blog that will help you further utilize JavaScript:
- JavaScript: a Tutorial on How to Index, Split, and Manipulate Strings
- Working with JavaScript: How Prototypes and Inheritances Operate
- A Tutorial on Working with JSON in JavaScript
- A Guide on Adding JavaScript to HTML
Happy Computing!
- How to Deploy WordPress with Persistent Volume on Kubernetes Cluster - March 17, 2023
- Deploying Applications on Kubernetes Using Argo CD and GitOps - October 26, 2022
- Using Node.js Modules with npm and package.json: A Tutorial - October 6, 2022
- Using Ansible to Install and Configure WordPress with LAMP on Ubuntu - September 23, 2022
- Creating Views in the Django Web Application Framework - September 22, 2022