Working with Objects in JavaScript

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 bind this to the object.
  • Prefer const for object declarations: Using const for objects prevents reassigning them, though properties can still be modified.

Exercises


  1. Creating and Accessing Object Properties
    • Objective: Practice creating an object and accessing its properties.
    • Instructions: Create an object called book with properties title, author, and year. Log the title and year properties to the console.
  2. Modifying and Adding Properties
    • Objective: Practice updating and adding properties to an object.
    • Instructions: Create an object called movie with properties title and director. Update the title and add a releaseYear property, then log the modified object.
  3. Defining Methods in an Object
    • Objective: Practice defining and calling methods.
    • Instructions: Create an object called rectangle with properties width and height. Add a method area that returns the area (width × height) and log the result.
  4. Using Nested Objects
    • Objective: Practice working with nested objects.
    • Instructions: Create an object called user with nested properties profile (containing name and email) and settings (containing theme and notifications). Log the email and theme properties.
  5. Looping Through Properties
    • Objective: Practice looping through an object’s properties.
    • Instructions: Create an object called city with properties name, population, and country. Use a for...in loop to log each property and its value.

Multiple-Choice Questions


  1. 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
    Answer: D. Both let obj = {}; and let obj = new Object(); are valid ways to create an object.
  2. What is the output of the following code?javascriptCopy codeconst person = { name: "Alice", age: 25 }; console.log(person.name);
    • A) Alice
    • B) undefined
    • C) 25
    • D) Error
    Answer: A. Alice, as person.name accesses the name property of the person object.
  3. 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()
    Answer: B. Object.keys() returns an array of property names of an object.
  4. How would you access the phone property inside contact 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"]
    Answer: A. person.contact.phone is the correct way to access the phone property in the nested contact object.
  5. 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.
    Answer: B. this in an object method refers to the object itself.