Objects in JavaScript
What Is an Object?
An object is a data structure that stores data in the form of key-value pairs. Objects are the foundation of almost every concept in JavaScript.
const student = {
studentId: "2024100123",
name: "John Smith",
major: "Information Technology",
semester: 3,
gpa: 3.75
};
console.log(student.name); // "John Smith"
console.log(student["major"]); // "Information Technology"
student.gpa = 3.80;
student.email = "[email protected]";
delete student.semester;
Object Methods
const student = {
studentId: "2024100123",
name: "John Smith",
scoreList: [85, 90, 78, 92, 88],
showProfile() {
return `Student ID: ${this.studentId}, Name: ${this.name}`;
},
calcAverage() {
const total = this.scoreList.reduce((sum, n) => sum + n, 0);
return Math.round((total / this.scoreList.length) * 100) / 100;
},
get classification() {
const average = this.calcAverage();
if (average >= 85) return "Cum Laude";
if (average >= 80) return "Very Satisfactory";
return "Satisfactory";
},
addScore(score) {
this.scoreList.push(score);
return `Score ${score} added!`;
}
};
console.log(student.showProfile());
console.log(student.calcAverage());
console.log(student.classification);
The this Keyword
this refers to the object currently being executed.
const student = {
name: "John Smith",
gpa: 3.75,
showInfo() {
console.log(`Name: ${this.name}, GPA: ${this.gpa}`);
}
};
student.showInfo();
// Arrow functions do NOT have their own this
const obj = {
value: 10,
add: (number) => {
// this.value is not accessible here
},
subtract(number) {
this.value -= number; // this works
}
};
Object Destructuring (ES6)
const student = {
studentId: "2024100123",
name: "John Smith",
major: "Information Technology",
gpa: 3.75
};
// Basic destructuring
const { studentId, name, gpa } = student;
console.log(studentId, name, gpa);
// Rename
const { name: studentName, major: program } = student;
console.log(studentName, program);
// Default value
const { address = "Unknown" } = student;
console.log(address);
// Rest properties
const { name: fullName, ...restData } = student;
console.log(restData);
// Nested destructuring
const academicData = {
student: { studentId: "2024100123", name: "John" },
gpa: 3.75
};
const {
student: { studentId: innerStudentId, name: innerName },
gpa: innerGpa
} = academicData;
console.log(innerStudentId, innerName, innerGpa);
// Parameter destructuring
function showProfile({ name, studentId, gpa = 0 }) {
console.log(`${name} (${studentId}) — GPA: ${gpa}`);
}
showProfile(student);
Nested Objects
const campus = {
name: "University of Indonesia",
faculty: {
fmipa: {
name: "Faculty of Mathematics and Natural Sciences",
major: {
if: {
name: "Information Technology",
accreditation: "A",
head: "Dr. Aaron, M.Cs"
},
si: {
name: "Information Systems",
accreditation: "A",
head: "Dr. John, M.Sc"
}
}
}
}
};
// Access deeply nested
console.log(campus.faculty.fmipa.major.if.name);
// "Information Technology"
// Safe access with optional chaining
console.log(campus?.faculty?.fti?.major?.if?.name); // undefined (no error)
Object.keys(), Object.values(), Object.entries()
const student = {
studentId: "2024100123",
name: "John Smith",
gpa: 3.75,
major: "Information Technology"
};
// Object.keys() — array of keys
const keys = Object.keys(student);
console.log(keys); // ["studentId", "name", "gpa", "major"]
// Object.values() — array of values
const values = Object.values(student);
console.log(values); // ["2024100123", "John Smith", 3.75, "Information Technology"]
// Object.entries() — array of [key, value] pairs
const entries = Object.entries(student);
console.log(entries);
// [["studentId", "2024100123"], ["name", "John Smith"], ...]
// Iterating with entries
for (const [key, value] of Object.entries(student)) {
console.log(`${key}: ${value}`);
}
// Object.hasOwn() — check whether a property exists (ES2022)
console.log(Object.hasOwn(student, "name")); // true
console.log(Object.hasOwn(student, "email")); // false
Spread Operator with Objects
// Copy an object
const student = {
studentId: "2024100123",
name: "John Smith",
gpa: 3.75
};
const studentCopy = { ...student };
console.log(studentCopy);
// Merge objects
const academicData = { semester: 3, creditsTaken: 18 };
const combined = { ...student, ...academicData };
console.log(combined);
// { studentId, name, gpa, semester, creditsTaken }
// Override a property
const update = { ...student, gpa: 3.80, email: "[email protected]" };
console.log(update);
Object.assign()
// Merge and copy
const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { d: 5 };
const result = Object.assign(target, source1, source2);
console.log(result); // { a: 1, b: 3, c: 4, d: 5 }
// Shallow copy
const copy = Object.assign({}, student);
Case Study: Student Profile Data with a Nested Address
const studentProfile = {
studentId: "2024100123",
name: "John Smith",
birthPlace: "New York",
birthDate: "2002-05-15",
gender: "Male",
address: {
street: "123 Sudirman Street",
rt: "003",
rw: "007",
district: "Manhattan",
city: "New York",
province: "West Java",
zipCode: "40115"
},
parents: {
father: {
name: "Smith",
job: "Self-employed",
income: 8000000
},
mother: {
name: "Sarah",
job: "Teacher",
income: 5000000
}
},
courses: [
{ code: "IF101", name: "Web Programming", credits: 3, score: 85 },
{ code: "IF102", name: "Database", credits: 3, score: 78 },
{ code: "IF103", name: "Algorithms", credits: 4, score: 92 }
],
calcTotalCredits() {
return this.courses.reduce((sum, c) => sum + c.credits, 0);
},
calcGPA() {
const totalWeight = this.courses.reduce((sum, c) => {
let weight;
if (c.score >= 85) weight = 4;
else if (c.score >= 80) weight = 3.5;
else if (c.score >= 75) weight = 3;
else weight = 2;
return sum + (weight * c.credits);
}, 0);
return Math.round((totalWeight / this.calcTotalCredits()) * 100) / 100;
},
get summary() {
const { name, studentId } = this;
const city = this.address.city;
const gpa = this.calcGPA();
const totalCredits = this.calcTotalCredits();
return `${name} (${studentId}) — ${city} — GPA: ${gpa} — ${totalCredits} credits`;
}
};
// Usage
console.log(studentProfile.summary);
console.log(`GPA: ${studentProfile.calcGPA()}`);
console.log(`Total credits: ${studentProfile.calcTotalCredits()}`);
// Nested destructuring
const {
name,
address: { city, province },
parents: { father: { name: fatherName } }
} = studentProfile;
console.log(`${name} from ${city}, ${province}`);
console.log(`Father: ${fatherName}`);
// Iterating properties
console.log("\n=== STUDENT DATA ===");
for (const [key, value] of Object.entries(studentProfile)) {
if (typeof value !== "function" && typeof value !== "object") {
console.log(`${key}: ${value}`);
}
}
Summary
| Concept | Function |
|---|---|
| Object literal | {} — create an object directly |
| Dot notation | obj.prop — access a property |
| Bracket notation | obj["prop"] — dynamic property access |
| Destructuring | const { a } = obj — extract a property |
| Spread | { ...obj } — copy/merge an object |
| Object.keys | Get all keys |
| Object.values | Get all values |
| Object.entries | Get all key-value pairs |
| this | Reference to the object itself |
| Nested | Objects inside objects |