Objects
Introduction
Objects in JavaScript are collections of key–value pairs. They allow us to group related data and behavior into one unit. Keys (also called properties) are usually strings, and values can be any type — numbers, strings, arrays, functions, or even other objects.
Objects are the backbone of JavaScript: everything from arrays to functions to classes is built on top of objects. Understanding objects is essential for structuring data and building larger programs.
Concepts
Creating Objects
- Object literals
const person = { name: "Alice", age: 25 };
- Using
new Object()(less common).
Accessing Properties
- Dot notation:
person.name. - Bracket notation:
person["name"](useful when keys are dynamic or not valid identifiers).
Adding & Modifying Properties
person.city = "London";
person.age = 26;
Deleting Properties
delete person.city;
Methods (functions inside objects)
const person = {
name: "Alice",
greet: function() {
return `Hi, I'm ${this.name}`;
}
};
Destructuring
const {name, age} = person;
Nested Objects
Objects can contain other objects:
const company = {
name: "TechCorp",
address: { city: "London", country: "UK" }
};
Examples
const car = { make:"Toyota", year:2020 };
car.color="Blue";
car.getAge = function(){
return new Date().getFullYear() - this.year;
};
const { make, year } = car;
Challenges
1. Create student object
- Create an object student with properties: name, age, and course. Print each property.
💡 Show Answer
const student={ name:"Alice", age:21, course: "Computer Science" };
console.log(student.name);
console.log(student.age);
console.log(student.course);
2. Add grade && Update age
- Add a new property grade to student and update the age.
💡 Show Answer
student.grade="A";
student.age=22;
3. Delete property
- Delete the Student isGraduate property.
💡 Show Answer
delete student.isGraduate;
console.log(JSON.stringify(student));
4. Add method getSummary
- Create an object book with a method getSummary() that returns a string combining its title and author.
💡 Show Answer
const book={
title:"Harry Potter",
author:"JK Rowling",
getSummary(){
return `The book ${this.title} was written by ${this.author}`;
}
};
console.log(book.getSummary());
5. Bracket notation
- Use bracket notation to access a property with a key that contains a space, e.g. "favorite color".
💡 Show Answer
const person = {
name: "Alice",
age: 25,
"favorite color": "blue" // key with a space
};
// ❌ Won’t work
// console.log(person.favorite color);
// ✅ Correct way
console.log(person["favorite color"]); // "blue"
6. Destructuring
- Create a car object with make and year properties.
- Use object destructuring to get the values of make and year, and then store them in variables.
💡 Show Answer
const car={make:"Toyota",year:2020};
const {make,year}=car;
7. Nested objects
- Create a library object with a books object.
- The books object will have two book objects contained inside it.
- Log the details of each of the books in the library.
💡 Show Answer
const library={books:{b1:{title:"One"},b2:{title:"Two"}}};
console.log(library.books.b1.title);
console.log(library.books.b2.title);
8. Count properties
- Write a function countProperties(obj) that returns how many properties an object has.
💡 Show Answer
function countProperties(obj){
return Object.keys(obj).length;
}
const student={
name:"Alice",
age:21,
isGraduate:true,
getSummary(){
return `Name: ${this.name} is ${this.age} years old. Has graduated = ${this.isGraduate}`;
}
};
console.log(countProperties(student));
9. Loop through keys/values
- Loop over an object’s keys and values using for...in.
💡 Show Answer
const student={
name:"Alice",
age:21,
isGraduate:true,
getSummary(){
return `Name: ${this.name} is ${this.age} years old. Has graduated = ${isGraduate}`;
}
};
for(let key in student){
console.log(key,student[key]);
}
10. Merge objects
- Merge two objects (contactInfo and personalInfo) into a new object using the spread operator (...).
💡 Show Answer
const contactInfo = { name: "Sean Bean", email: "sbean@actorsguild.com", telephone: "07354635456"};
const personalInfo = { name: "Sean Bean", address1: "Some Street", number: 42, postcode: "L346DF", county: "Merseyside"};
const mergedContact = {...contactInfo, ...personalInfo};
console.log(`Merged Contact Details: ${mergedContact}`);
You will have noticed some issues.
- The objects have not been fully copied.
- Name is repeated in both objects, so only the last name value is stored.
How can you solve this problem?
Instead of merging the two contact objects into a single object what about: Merging them into a new object with two properties.
- mergedContact which is the contact object destructured.
- mergedPersonal which is the personal object destructured. This gives a new solution with both objects stored in the single merged object as properties.
💡 Show Answer
const contactInfo = { name: "Sean Bean", email: "sbean@actorsguild.com", telephone: "07354635456"};
const personalInfo = { name: "Sean Bean", address1: "Some Street", number: 42, postcode: "L346DF", county: "Merseyside"};
const mergedContact = {contact:{...contactInfo}, personal:{...personalInfo}};
console.log(`Merged Contact Details: ${JSON.stringify(mergedContact)}`);