Module 5: Arrays, Objects, and Collections
Objects and Property Access
Model related data with object properties, methods, and safe property access.
Objects store related data as key-value properties. Use dot notation when the property name is known and identifier-like, and bracket notation for dynamic keys or keys with spaces.
const learner = {
name: "Asha",
level: "beginner",
completedLessons: 4,
introduce() {
return `I am ${this.name}`;
},
};
console.log(learner.name);
console.log(learner["level"]);
console.log(learner.introduce());
Updating and checking#
Properties can be added, updated, or deleted, although deleting properties is not a routine way to manage application state. Use Object.hasOwn(object, key) to check for an own property, including when its value is undefined.
const settings = { theme: "light" };
settings.theme = "dark";
settings.language = "en";
console.log(Object.hasOwn(settings, "theme"));
The in operator also checks inherited properties, while Object.hasOwn checks only the object's own properties.
Copying and freezing#
{ ...object } creates a shallow copy of enumerable own properties. Object.freeze prevents changes to an object's own property descriptors at the top level, but it is shallow and not a universal security boundary.
Destructuring preview#
const { name, level } = learner extracts values into bindings. The next lesson covers destructuring, spread, and rest in more detail.
Practice#
Create a book object with a title, author, and page count. Add a method that returns a short description and test access to a missing property.