Objects are collections of key-value pairs (properties and methods). Keys are strings or Symbols, and values can be any JavaScript data type, including primitive values, arrays, nested objects, or functions (methods).
flowchart LR
Obj["User Object"] --> Prop1["Property: id (101)"]
Obj --> Prop2["Property: username ('alex')"]
Obj --> Method1["Method: getFullName()"]
Obj --> Computed["Computed Key: ['role_' + id]"]
| Syntax | Example | Description |
|---|---|---|
| Dot Notation | user.name |
Clean syntax; key must be a valid identifier. |
| Bracket Notation | user["user-role"] |
Mandatory for dynamic key evaluation or keys with special characters/spaces. |
| Computed Property Name | {[dynamicKey]: value} |
Creates object keys dynamically at object creation time. |
Object.keys(obj) |
Object.keys(user) |
Returns array of object's own enumerable string property keys. |
// Demonstrating Object Literals, Methods, and Utility Methods
const dynamicRoleKey = "user_role";
const userProfile = {
id: 501,
firstName: "Maksudur",
lastName: "Rahman",
// Computed property key
[dynamicRoleKey]: "Lead Architect",
// Method definition shorthand
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
};
// Accessing properties
console.log(`Full Name: ${userProfile.getFullName()}`);
console.log(`Role (Bracket Access): ${userProfile[dynamicRoleKey]}`);
// Adding and deleting properties
userProfile.lastLogin = new Date().toISOString();
delete userProfile.lastName; // Delete property
// Object Utility Inspections
console.log("Keys:", Object.keys(userProfile));
console.log("Values:", Object.values(userProfile));
console.log("Entries:", Object.entries(userProfile));
// Merging Objects with Object.assign() or Spread
const defaultPermissions = { canEdit: true, canDelete: false };
const mergedUser = { ...userProfile, ...defaultPermissions };
console.log("Merged User Profile:", mergedUser);
methodName() {} instead of methodName: function() {} inside object literals.this in Object Methods: Arrow functions inside objects do NOT bind this to the object instance; they inherit this from the outer scope.hasOwnProperty() or Object.hasOwn(): Check if a property exists directly on the object rather than its prototype chain using Object.hasOwn(obj, "prop").Write an object car with properties brand, model, and a method getSpecs() returning "Brand Model". Explain what happens if getSpecs is written as an arrow function.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.