Assignments Of Day 9: Objects in JavaScript
These exercises will help reinforce your understanding of objects in JavaScript.
4o mini
You said:
Give some assignments with solutions from same concept above
ChatGPT said:
ChatGPT
Assignments on Objects in JavaScript
Here are a few assignments to help you practice the concept of objects in JavaScript. Each assignment is followed by a detailed solution.
Assignment 1: Create an Object for a Book
Task:
Create an object called book that contains the following properties:
- title (a string)
- author (a string)
- price (a number)
Then, add a method called getBookInfo() that returns a string in the following format:
"Title: <title>, Author: <author>, Price: <price>"
Solution:
javascript
Copy code
let book = {
title: "To Kill a Mockingbird",
author: "Harper Lee",
price: 15.99,
// Method to get book info
getBookInfo: function() {
return `Title: ${this.title}, Author: ${this.author}, Price: ${this.price}`;
}
};
// Calling the method
console.log(book.getBookInfo()); // Output: Title: To Kill a Mockingbird, Author: Harper Lee, Price: 15.99
Assignment 2: Add and Remove Properties
Task:
Create an object student with the following properties:
- name (a string)
- age (a number)
- course (a string)
Then:
1. Add a new property grade to the student object.
2. Remove the age property from the student object.
3. Display the updated student object.
Solution:
javascript
Copy code
let student = {
name: "John",
age: 20,
course: "Mathematics"
};
// Add a new property 'grade'
student.grade = "A";
// Remove the 'age' property
delete student.age;
// Display the updated object
console.log(student); // Output: { name: 'John', course: 'Mathematics', grade: 'A' }
Assignment 3: Access Properties Using Both Dot and Bracket Notation
Task:
Create an object car with the following properties:
- make (string)
- model (string)
- year (number)
Then, access the properties using both dot notation and bracket notation and log the results to the console.
Solution:
javascript
Copy code
let car = {
make: "Honda",
model: "Civic",
year: 2020
};
// Access properties using dot notation
console.log(car.make); // Output: Honda
console.log(car.model); // Output: Civic
// Access properties using bracket notation
console.log(car["year"]); // Output: 2020
Assignment 4: Create a Method to Calculate and Return Age
Task:
Create an object called person with the following properties:
- name (a string)
- birthYear (a number)
Then, add a method called getAge() that calculates the person's current age (using 2024 as the current year) and returns it.
Solution:
javascript
Copy code
let person = {
name: "Alice",
birthYear: 1995,
// Method to calculate age
getAge: function() {
let currentYear = 2024;
return currentYear - this.birthYear;
}
};
// Calling the method to get the age
console.log(person.getAge()); // Output: 29
Assignment 5: Manipulate an Object with Nested Properties
Task:
Create an object company with the following nested structure:
- name (a string)
- location (a string)
- employees (an array of objects, each with name and role)
Then:
1. Add a new employee object to the employees array.
2. Remove the location property from the company object.
3. Display the updated company object.
Solution:
javascript
Copy code
let company = {
name: "TechCorp",
location: "New York",
employees: [
{ name: "John Doe", role: "Developer" },
{ name: "Jane Smith", role: "Designer" }
]
};
// Add a new employee
company.employees.push({ name: "Mark Lee", role: "Manager" });
// Remove the 'location' property
delete company.location;
// Display the updated company object
console.log(company);
/*
Output:
{
name: 'TechCorp',
employees: [
{ name: 'John Doe', role: 'Developer' },
{ name: 'Jane Smith', role: 'Designer' },
{ name: 'Mark Lee', role: 'Manager' }
]
}
*/
Assignment 6: Use a Method with Parameters
Task:
Create an object rectangle with the following properties:
- width (a number)
- height (a number)
Then, add a method calculateArea() that calculates the area of the rectangle using the formula width * height and returns the area. Call the method with the values width = 10 and height = 5 and log the result.
Solution:
javascript
Copy code
let rectangle = {
width: 10,
height: 5,
// Method to calculate area
calculateArea: function() {
return this.width * this.height;
}
};
// Calling the method to calculate the area
console.log(rectangle.calculateArea()); // Output: 50
Assignment 7: Combining Methods and Properties
Task:
Create an object employee with the following properties:
- name (a string)
- role (a string)
- salary (a number)
Then, add a method giveRaise() that takes a percentage and increases the salary by that percentage. Finally, display the updated salary after a raise of 10%.
Solution:
javascript
Copy code
let employee = {
name: "Sarah",
role: "Software Engineer",
salary: 60000,
// Method to give a raise
giveRaise: function(percentage) {
this.salary += (this.salary * percentage / 100);
}
};
// Give a 10% raise
employee.giveRaise(10);
// Display the updated salary
console.log(employee.salary); // Output: 66000
Assignment 8: Nested Objects and Accessing Nested Properties
Task:
Create an object student with the following structure:
- name (string)
- address (object with properties street, city, zip)
- courses (array of strings)
Then, access and display the street and city from the address property.
Solution:
javascript
Copy code
let student = {
name: "Emily",
address: {
street: "123 Main St",
city: "Los Angeles",
zip: "90001"
},
courses: ["Math", "Science", "History"]
};
// Accessing nested properties
console.log(student.address.street); // Output: 123 Main St
console.log(student.address.city); // Output: Los Angeles
Summary of Solutions:
- The solutions above demonstrate the core concepts of working with objects, methods, adding/removing properties, and accessing properties both directly and through methods.
- Each example shows practical use cases for handling objects in JavaScript, which is crucial for real-world application development.
4o mini
You said:
more
ChatGPT said:
ChatGPT
Here are additional assignments with solutions on the concept of objects in JavaScript.
Assignment 9: Create a Student Object with Methods
Task:
Create an object student with the following properties:
- firstName (string)
- lastName (string)
- marks (array of numbers)
Then, add the following methods to the object:
1. getFullName() - Returns the full name of the student.
2. calculateAverage() - Calculates and returns the average of the marks.
Solution:
javascript
Copy code
let student = {
firstName: "Anna",
lastName: "Smith",
marks: [85, 90, 88, 92],
// Method to get full name
getFullName: function() {
return `${this.firstName} ${this.lastName}`;
},
// Method to calculate average marks
calculateAverage: function() {
let total = this.marks.reduce((sum, mark) => sum + mark, 0);
return total / this.marks.length;
}
};
// Calling the methods
console.log(student.getFullName()); // Output: Anna Smith
console.log(student.calculateAverage()); // Output: 88.75
Assignment 10: Count the Number of Properties in an Object
Task:
Create an object person with at least 4 properties. Write a function countProperties() that takes the object as an argument and returns the number of properties in that object.
Solution:
javascript
Copy code
let person = {
name: "Jack",
age: 30,
occupation: "Engineer",
city: "London"
};
// Function to count properties
function countProperties(obj) {
return Object.keys(obj).length;
}
console.log(countProperties(person)); // Output: 4
Assignment 11: Update a Property in an Object
Task:
Create an object car with the following properties:
- make (string)
- model (string)
- year (number)
Then, update the year property to a new value and log the updated car object.
Solution:
javascript
Copy code
let car = {
make: "Toyota",
model: "Corolla",
year: 2021
};
// Update the 'year' property
car.year = 2023;
// Log the updated object
console.log(car); // Output: { make: 'Toyota', model: 'Corolla', year: 2023 }
Assignment 12: Object Inside an Array
Task:
Create an array called products that contains three objects. Each object should represent a product with the following properties:
- id (number)
- name (string)
- price (number)
Then, write a function getTotalPrice() that calculates and returns the total price of all the products.
Solution:
javascript
Copy code
let products = [
{ id: 1, name: "Laptop", price: 899 },
{ id: 2, name: "Phone", price: 699 },
{ id: 3, name: "Headphones", price: 199 }
];
// Function to calculate the total price
function getTotalPrice(products) {
return products.reduce((total, product) => total + product.price, 0);
}
console.log(getTotalPrice(products)); // Output: 1797
Assignment 13: Create and Manipulate a Nested Object
Task:
Create an object team that represents a sports team. The object should contain:
- teamName (string)
- players (array of objects, each player having name, age, and position)
Then:
1. Add a new player to the players array.
2. Update a player's position.
3. Remove a player from the players array.
Solution:
javascript
Copy code
let team = {
teamName: "Warriors",
players: [
{ name: "John", age: 28, position: "Forward" },
{ name: "Mike", age: 24, position: "Guard" }
]
};
// Add a new player
team.players.push({ name: "Sarah", age: 26, position: "Center" });
// Update a player's position
team.players[1].position = "Small Forward";
// Remove a player
team.players.splice(0, 1);
// Display the updated team
console.log(team.players);
/* Output:
[
{ name: 'Mike', age: 24, position: 'Small Forward' },
{ name: 'Sarah', age: 26, position: 'Center' }
]
*/
Assignment 14: Check if a Property Exists in an Object
Task:
Create an object book with properties title, author, and yearPublished. Write a function hasProperty(obj, property) that checks if a given property exists in the object. Return true if the property exists, otherwise false.
Solution:
javascript
Copy code
let book = {
title: "JavaScript for Beginners",
author: "John Doe",
yearPublished: 2020
};
// Function to check if a property exists
function hasProperty(obj, property) {
return property in obj;
}
console.log(hasProperty(book, "title")); // Output: true
console.log(hasProperty(book, "price")); // Output: false
Assignment 15: Clone an Object
Task:
Create an object person with the following properties:
- name (string)
- age (number)
Write a function cloneObject(obj) that creates a copy of the object and returns it. Then, change one property in the cloned object and display both objects to verify they are independent.
Solution:
javascript
Copy code
let person = {
name: "Alice",
age: 30
};
// Function to clone an object
function cloneObject(obj) {
return { ...obj };
}
// Clone the 'person' object
let clonedPerson = cloneObject(person);
// Modify the cloned object
clonedPerson.age = 35;
// Display both objects
console.log(person); // Output: { name: 'Alice', age: 30 }
console.log(clonedPerson); // Output: { name: 'Alice', age: 35 }
Assignment 16: Iterate Over Object Properties
Task:
Create an object student with the following properties:
- name (string)
- age (number)
- course (string)
Write a function printProperties(obj) that iterates over the object properties and logs each key-value pair to the console.
Solution:
javascript
Copy code
let student = {
name: "John",
age: 22,
course: "Computer Science"
};
// Function to iterate over object properties
function printProperties(obj) {
for (let key in obj) {
console.log(`${key}: ${obj[key]}`);
}
}
printProperties(student);
/*
Output:
name: John
age: 22
course: Computer Science
*/
Assignment 17: Merge Two Objects
Task:
Create two objects, person and contact, with the following properties:
- person: name (string), age (number)
- contact: phone (string), email (string)
Merge the two objects into a new object and display the result.
Solution:
javascript
Copy code
let person = {
name: "Sarah",
age: 27
};
let contact = {
phone: "123-456-7890",
email: "sarah@example.com"
};
// Merge the objects
let mergedObject = { ...person, ...contact };
console.log(mergedObject);
/* Output:
{
name: 'Sarah',
age: 27,
phone: '123-456-7890',
email: 'sarah@example.com'
}
*/
Assignment 18: Object Method to Update Multiple Properties
Task:
Create an object employee with the following properties:
- name (string)
- role (string)
- salary (number)
Add a method updateDetails() that accepts an object with updated properties and updates the employee's details. The method should return the updated object.
Solution:
javascript
Copy code
let employee = {
name: "Emily",
role: "Manager",
salary: 50000,
// Method to update employee details
updateDetails: function(updatedDetails) {
for (let key in updatedDetails) {
if (this.hasOwnProperty(key)) {
this[key] = updatedDetails[key];
}
}
return this;
}
};
// Update the employee's details
let updatedEmployee = employee.updateDetails({ role: "Senior Manager", salary: 60000 });
console.log(updatedEmployee);
// Output: { name: 'Emily', role: 'Senior Manager', salary: 60000 }
