Objects, Methods, and the this Keyword
Objects represent real-world entities with properties (data) and methods (actions).
What is it?
A JavaScript object is an unordered collection of key-value pairs. Keys are strings (or symbols), and values can be any data type including functions (called methods).
Why is it used?
Structures complex models like User Profiles, Course Curriculums, Settings, and API records.
Detailed Explanation
Object Basics:
• Object Literal syntax: `const obj = { key: value };`.
• Accessing Properties: Dot notation (`obj.title`) or bracket notation (`obj["title"]` - required for dynamic keys).
• Methods: Functions stored as object properties.
• The `this` Keyword: Inside an object method, `this` refers to the object executing the method.
• Object Utilities: `Object.keys(obj)`, `Object.values(obj)`, `Object.entries(obj)`.
Syntax Structure
Syntax Blueprint
const student = {
name: "Pooja",
course: "Python",
getDetails() {
return `${this.name} is enrolled in ${this.course}`;
}
};
Code Example
JAVASCRIPT Code
const institute = {
name: "IGM Computer Institute",
city: "Nanded",
established: 2012,
courses: ["Python", "Excel", "Data Analytics", "C++"],
// Object Method
getSummary() {
return `${this.name} (${this.city}) offers ${this.courses.length} certified courses.`;
},
// Method adding a course
addCourse(newCourse) {
this.courses.push(newCourse);
console.log(`Added ${newCourse}. Total now: ${this.courses.length}`);
}
};
console.log(institute.getSummary());
institute.addCourse("Full-Stack Web Dev");
console.log("Available keys:", Object.keys(institute));
Explanation of the Code
• `this.name` accesses the `name` property of the `institute` object.
• `addCourse` modifies internal state.
• `Object.keys()` lists all defined properties.
Expected Output
IGM Computer Institute (Nanded) offers 4 certified courses.
Added Full-Stack Web Dev. Total now: 5
Available keys: [ 'name', 'city', 'established', 'courses', 'getSummary', 'addCourse' ]
Real-World Application
Every JSON API returns data as JavaScript objects and arrays.
Common Mistakes to Avoid
• Using an arrow function as an object method and expecting `this` to work (arrow functions do not bind their own `this`; they capture `this` from the outer scope).
• Trying to read properties on `undefined` (e.g. `user.profile.avatar` when `profile` is undefined throws error). Use Optional Chaining `user?.profile?.avatar`.
Quick Practice Challenge
Create a `car` object with `brand`, `model`, `year`, and a `getInfo()` method returning a formatted string.
Key Takeaways
• Objects store structured key-value data.
• Inside standard methods, `this` points to the owning object.
• Use Optional Chaining (`?.`) to safely access deeply nested properties.