Exercise Objects JavaScript
Exercise Objects JavaScript
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
1
● Deleting Properties
● Iterating Over Properties
● Property Existence Check
● Working with Nested Objects
● Copying Objects
● Merging Objects
● Extracting Object Keys and Values
Each exercise is accompanied by a solution and a detailed explanation, making it
perfect for both learning and teaching. 📚💡
Problem: Create an object named car with properties make, model, and year.
Then, access and log the model property.
Solution:
let car = {
make: 'Toyota',
model: 'Camry',
year: 2020
};
console.log(car.model); // Output: Camry
Explanation: This exercise demonstrates the creation of an object and accessing
one of its properties using dot notation.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
2
Exercise: Modifying Object Properties
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
3
Exercise: Iterating Over Object Properties
Problem: Write a loop that logs all properties and their values of the car object.
Solution:
for (let key in car) {
console.log(key + ': ' + car[key]);
}
Explanation: The for...in loop is used to iterate over all enumerable properties of
an object.
Problem: Create an object person with properties name and address, where
address is an object with properties street, city, and zipCode.
Solution:
let person = {
name: 'Alice',
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
4
address: {
street: '123 Main St',
city: 'Anytown',
zipCode: '12345'
}
};
console.log(person.address.city); // Output: Anytown
Explanation: This demonstrates how to create nested objects and access
properties within them.
Problem: Merge two objects, person and contactDetails (with properties email
and phone), into a new object.
Solution:
let contactDetails = {
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
5
email: 'alice@example.com',
phone: '1234567890'
};
let mergedObject = Object.assign({}, person, contactDetails);
console.log(mergedObject);
Explanation: Object.assign can also be used to merge multiple objects into a new
object.
Problem: Get all keys and values from the person object separately and log them.
Solution:
let keys = Object.keys(person);
let values = Object.values(person);
console.log('Keys:', keys); // Output: Keys: ['name', 'address']
console.log('Values:', values); // Output: Values: ['Alice', {...}]
Explanation: Object.keys and Object.values are used to get an array of an object's
keys and values, respectively.
Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
6