Welcome to another tutorial, here you will learn how to create and use objects in JavaScript.
JavaScript is an object-based language and almost everything is an object or acts as an object in it. To achieve effective and efficient use of JavaScript, we
need to understand how objects work and also, how to create your objects and apply them.
In JavaScript named values are referred to as properties of the object, it is simply the collection of named values. From our previous tutorial on JavaScript arrays, you learned that an array is a collection of values. This set of values has an index (or numeric key) that starts from zero and increases by one for each value. Though, an object can be likened to an array but differs on the bases that you define the keys yourself, for instance, age, sex, and so on.
The sections below will review a lot of things about objects in detail.
In JavaScript, objects can be created with curly brackets {} with an optional list of properties. These properties are "key: value" pairs, where the key (known as property name) is always a string, and the value (also known as property value) can be any data type, like numbers, strings, Booleans, or complex data types like functions, arrays, and other objects.
More so, properties with functions as their values are often called methods that will distinguish them from other properties. Below is an example of what a typical JavaScript object may look like;
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
From the example above, an object called a person was created that has three properties name, age, and gender, and one method displayName().
The method displayName() displayed the value of this. name, which resolves to person. name. In JavaScript, it is the easiest and preferred way to create a new object, which is known as object literals syntax.
In general, property names do not need to be quoted except they are reserved words, if they contain spaces or special characters (anything other than letters, numbers, and the _ and $ characters), or if they start with a number, as shown in the illustration below:
var person = {
"first name": "Peter",
"current age": 28,
gender: "Male"
};
Note: From ECMAScript 5, reserved words can be used as object's property names without quoting. But, you should avoid doing this for better compatibility with programmed language.
To get access to the property of a value, you use the dot(.), or ([]) notation. This is shown in the example:
var book = {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000
};
// Dot notation
document.write(book.author); // Prints: J. K. Rowling
// Bracket notation
document.write(book["year"]); // Prints: 2000
The dot notation is simpler to read and write, however, it cannot always be used. This is because if the name of the property is not valid (meaning if it contains spaces or special characters), the dot notation cannot be used; so the bracket notation is what you can use. Let’s take a look at this example:
var book = {
name: "Harry Potter",
author: "J. K. Rowling",
"publication date": "12 Aug 2022"
};
// Bracket notation
document.write(book["publication date"]); // Prints: 12 Aug 2022
Note: The square bracket notation offers much greater flexibility than the dot notation. It makes it possible to property names as variables instead of just string literals, as shown in the following example below:
var person = {
name: "Jervis",
age: 28,
gender: "Male"
};
var key = prompt("Enter any property name to get its value");
alert(person[key]); // Outputs: Peter (if enter "name")
In looping, the for… in loop is used to iterate through the key-value pairs of an object. Below is an example
var person = {
name: "Peter",
age: 28,
gender: "Male"
};
// Iterating over object properties
for(var i in person) {
document.write(person[i] + "<br>"); // Prints: name, age and gender
}
You can set the new properties or update the existing property by using the dot(.) or square bracket ([]) notation, as demonstrated in the example below:
var person = {
name: "Peter",
age: 28,
gender: "Male"
};
// Setting a new property
person.country = "United States";
document.write(person.country); // Prints: United States
person["email"] = "[email protected]";
document.write(person.email); // Prints: [email protected]
// Updating existing property
person.age = 24;
document.write(person.age); // Prints: 24
person["name"] = "Justin Drake";
document.write(person.name); // Prints: Justin Drake
The property from an object can be deleted with the delete operator. It is the only way to remove a property from an object. However, setting the property to null or undefined only changes the value of the property, and does not remove the property from the object.
var person = {
name: "Justin",
age: 26,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
// Deleting property
delete person.age;
alert(person.age); // Outputs: undefined
Note: The delete operator does not affect variables or declared functions, it only removes an object property or array element. Usually, you avoid the use of the delete operator for deleting an array element, as it doesn't change the array's length, rather, it leaves a hole in the array.
An object's method is accessed the same way as you would access properties by making use of the square bracket notation or the dot notation. It is shown below.
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
person.displayName(); // Outputs: Peter
person["displayName"](); // Outputs: Peter
JavaScript objects are reference types which means when you make copies of them, you end up copying the references to that object. But, original values like strings and numbers are assigned or copied as a whole value. The example below will help to better understand all this:
var message = "Hello World!";
var greet = message; // Assign message variable to a new variable
greet = "Hi, there!";
document.write(message); // Prints: Hello World!
document.write(greet); // Prints: Hi, there!
From the example above, we have made a copy of a variable message, while changing the value of that copy (i.e variable greet). The two variables remain distinct and separate, however, if we do the same thing with an object, we will get a different return. This is shown in the example here:
var person = {
name: "Peter",
age: 28,
gender: "Male"
};
var user = person; // Assign person variable to a new variable
user.name = "Harry";
document.write(person.name); // Prints: Harry
document.write(user.name); // Prints: Harry
You can see, that any changes made to the variable user also change the person variable. This is experienced because both variables reference the same object. Therefore, you can understand that copying the object does not clone it, but copies the reference to that object.