JavaScript is built on objects, meaning nearly everything in JavaScript behaves like or is an object. To work effectively with JavaScript, it's crucial to grasp how objects function and how to create and utilize your own objects.
A JavaScript object serves as a container for named values, commonly referred to as properties. Recall from our discussion on JavaScript arrays that an array is a collection of values, each with a numeric index starting from zero and increasing by one for each subsequent value. An object resembles an array but with the distinction that you define the keys yourself, such as name, age, gender, and so forth. In the upcoming sections, we'll delve into objects more thoroughly.
You can fashion an object using curly braces {}
, optionally accompanied by a list of properties. Each property is expressed as a "key: value" pair, where the key (or property name) is invariably a string, and the value (or property value) can be any data type, including strings, numbers, Booleans, or more complex data types like arrays, functions, and other objects. Furthermore, properties containing functions as their values are commonly termed methods to set them apart from other properties. Here's a typical JavaScript object:
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
In the provided example, an object named person
is crafted with three properties: name
, age
, and gender
, along with one method named displayName()
. The displayName()
method showcases the value of this.name
, which resolves to person.name
. This method represents the simplest and recommended approach to instantiate a new object in JavaScript, known as the object literals syntax.
Normally, property names don't require quotation marks unless they are reserved words, contain spaces or special characters (anything apart from letters, numbers, _
, and $
), or begin with a number, as demonstrated in the subsequent example:
var person = {
"first name": "Peter",
"current age": 28,
gender: "Male"
};
Note: Starting from ECMAScript 5, reserved words can be employed as property names for objects without quotation marks. Nonetheless, it's advisable to refrain from this practice to ensure improved compatibility.
To retrieve or obtain the value of a property, you have two options: the dot (.
) notation or the square bracket ([]
) notation, as illustrated in the example below:
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
While the dot notation is more straightforward to comprehend and employ, it's not always applicable. If the property name is invalid (e.g., containing spaces or special characters), the dot notation cannot be utilized. In such cases, you must resort to the bracket notation, as demonstrated below:
var book = {
name: "Harry Potter and the Goblet of Fire",
author: "J. K. Rowling",
"publication date": "8 July 2000"
};
// Bracket notation
document.write(book["publication date"]); // Prints: 8 July 2000
The square bracket notation provides greater flexibility compared to the dot notation. It enables you to specify property names as variables rather than just string literals, as depicted in the following example:
var person = {
name: "Peter",
age: 28,
gender: "Male"
};
var key = prompt("Enter any property name to get its value");
alert(person[key]); // Outputs: Peter (if enter "name")
You can traverse through the key-value pairs of an object using the for...in
loop. This loop is specifically optimized for iterating over an object's properties. Here's 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
}
In the same way, you can add new properties or modify existing ones using either the dot (.
) or bracket ([]
) notation, as shown 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"] = "peterparker@mail.com";
document.write(person.email); // Prints: peterparker@mail.com
// Updating existing property
person.age = 30;
document.write(person.age); // Prints: 30
person["name"] = "Peter Parker";
document.write(person.name); // Prints: Peter Parker
The delete
operator is used to completely remove properties from an object. Deleting is the only method to actually eliminate a property from an object. Setting the property to undefined
or null
merely changes the property's value without removing it from the object.
var person = {
name: "Peter",
age: 28,
gender: "Male",
displayName: function() {
alert(this.name);
}
};
// Deleting property
delete person.age;
alert(person.age); // Outputs: undefined
Note: The delete
operator only removes a property from an object or an element from an array. It does not impact variables or functions that have been declared. However, it's best to avoid using the delete
operator to remove an array element because it doesn't adjust the array's length, it simply creates an empty slot in the array.
You can call an object's method just like accessing its properties—using either the dot notation or the square bracket notation. Here's an example:
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, meaning when you copy them, you are actually copying the reference to that object, not the object itself. In contrast, primitive values such as strings and numbers are assigned or copied as whole values. To clarify this concept, let's look at the following example:
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!
In the example above, we created a copy of the variable message
and modified the value of that copy (i.e., the variable greet
). The two variables remain independent and separate. However, if we perform the same action with an object, the result will be different, as shown in the example below:
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
As you can see, any changes made to the variable user
also affect the person
variable. This occurs because both variables refer to the same object. Therefore, copying the object does not create a clone but instead copies the reference to that object.