An object in JavaScript is a data structure that allows you to store collections of data and functionality using key-value pairs. Objects can represent real-world entities, configurations, or group data logically, making them a crucial component of JavaScript programming. In this chapter, we’ll explore how to create and manipulate objects, work with properties and methods, and nest objects to create more complex structures.
1. Creating and Accessing Object Properties
An object is created using curly braces {}
, with each key-value pair separated by a comma. Properties are the values associated with an object, and each property has a unique key.
Creating an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
occupation: "Developer"
};
In this example, the person
object has four properties: firstName
, lastName
, age
, and occupation
.
Accessing Properties
You can access object properties using dot notation or bracket notation.
- Dot Notation: The most common and readable way to access properties.
- Bracket Notation: Useful when the property name is dynamic or contains special characters.
console.log(person.firstName); // Output: "John"
console.log(person["lastName"]); // Output: "Doe"
2. Modifying and Adding Properties
You can modify existing properties or add new properties to an object.
Modifying Properties
person.age = 31;
console.log(person.age); // Output: 31
Adding New Properties
person.email = "john.doe@example.com";
console.log(person.email); // Output: "john.doe@example.com"
In this example, a new email
property is added to the person
object.
3. Object Methods
Methods are functions that are defined as properties on an object. This allows you to group related functionality with the data it operates on, making code more modular and organized.
Defining Methods
You can define a method in an object by assigning a function to a property. You can also use ES6 shorthand syntax to define methods.
const calculator = {
add: function(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // Output: 8
console.log(calculator.subtract(10, 6)); // Output: 4
In this example, calculator
has two methods: add
and subtract
.
The this
Keyword
Inside methods, the this
keyword refers to the object itself, allowing methods to access other properties within the object.
const car = {
make: "Toyota",
model: "Camry",
year: 2020,
getDescription() {
return `${this.year} ${this.make} ${this.model}`;
}
};
console.log(car.getDescription()); // Output: "2020 Toyota Camry"
In this example, getDescription
uses this
to access other properties within the car
object.
4. Nesting Objects
Objects can contain other objects as properties, creating a nested structure. This allows for organizing complex data hierarchically.
Example of Nested Objects
const student = {
name: "Alice",
age: 22,
contact: {
email: "alice@example.com",
phone: "123-456-7890"
},
courses: {
math: { grade: "A", credits: 3 },
science: { grade: "B", credits: 4 }
}
};
console.log(student.contact.email); // Output: "alice@example.com"
console.log(student.courses.math.grade); // Output: "A"
In this example, the student
object contains nested objects within the contact
and courses
properties.
5. Looping Through Object Properties
You can loop through an object’s properties using the for...in
loop or Object.keys
/Object.values
.
Using for...in
Loop
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
This code logs each property name and value in the person
object.
Using Object.keys
, Object.values
, and Object.entries
Object.keys(object)
: Returns an array of the object’s property names.Object.values(object)
: Returns an array of the object’s property values.Object.entries(object)
: Returns an array of key-value pairs.
console.log(Object.keys(person)); // Output: ["firstName", "lastName", "age", "occupation"]
console.log(Object.values(person)); // Output: ["John", "Doe", 31, "Developer"]
console.log(Object.entries(person)); // Output: [["firstName", "John"], ["lastName", "Doe"], ["age", 31], ["occupation", "Developer"]]
6. Best Practices for Working with Objects
- Use meaningful property names: Make properties descriptive to clarify what data they hold.
- Avoid using
this
with arrow functions in methods: Arrow functions don’t bindthis
to the object. - Prefer
const
for object declarations: Usingconst
for objects prevents reassigning them, though properties can still be modified.
Exercises
- Creating and Accessing Object Properties
- Objective: Practice creating an object and accessing its properties.
- Instructions: Create an object called
book
with propertiestitle
,author
, andyear
. Log thetitle
andyear
properties to the console.
- Modifying and Adding Properties
- Objective: Practice updating and adding properties to an object.
- Instructions: Create an object called
movie
with propertiestitle
anddirector
. Update thetitle
and add areleaseYear
property, then log the modified object.
- Defining Methods in an Object
- Objective: Practice defining and calling methods.
- Instructions: Create an object called
rectangle
with propertieswidth
andheight
. Add a methodarea
that returns the area (width × height) and log the result.
- Using Nested Objects
- Objective: Practice working with nested objects.
- Instructions: Create an object called
user
with nested propertiesprofile
(containingname
andemail
) andsettings
(containingtheme
andnotifications
). Log theemail
andtheme
properties.
- Looping Through Properties
- Objective: Practice looping through an object’s properties.
- Instructions: Create an object called
city
with propertiesname
,population
, andcountry
. Use afor...in
loop to log each property and its value.
Multiple-Choice Questions
- Which of the following is the correct syntax for creating an object in JavaScript?
- A)
let obj = {};
- B)
let obj = [];
- C)
let obj = new Object();
- D) Both A and C
let obj = {};
andlet obj = new Object();
are valid ways to create an object. - A)
- What is the output of the following code?javascriptCopy code
const person = { name: "Alice", age: 25 }; console.log(person.name);
- A)
Alice
- B)
undefined
- C)
25
- D)
Error
Alice
, asperson.name
accesses thename
property of theperson
object. - A)
- Which method is used to get an array of property names of an object?
- A)
Object.values()
- B)
Object.keys()
- C)
Object.entries()
- D)
Object.props()
Object.keys()
returns an array of property names of an object. - A)
- How would you access the
phone
property insidecontact
in the following nested object?javascriptCopy codeconst person = { name: "John", contact: { email: "john@example.com", phone: "123-456-7890" } };
- A)
person.contact.phone
- B)
person.phone
- C)
person["phone"]
- D)
person.contact["email"]
person.contact.phone
is the correct way to access thephone
property in the nestedcontact
object. - A)
- Which of the following is true about
this
in an object method?- A) It refers to the global object in strict mode.
- B) It refers to the parent object that contains the method.
- C) It refers to the next sibling property.
- D) It is undefined by default.
this
in an object method refers to the object itself.
