Welcome, intrepid JavaScript explorers! This chapter equips you with the knowledge to navigate the fascinating world of objects and unlock their hidden treasures – their properties. Objects store collections of data under unique names, and this chapter empowers you to retrieve and utilize this valuable information.
.) and then the property name
const person = {
firstName: "Alice",
lastName: "Smith",
age: 30
};
const firstName = person.firstName;
console.log(firstName); // Output: Alice
person with three properties.firstName property, we use person.firstName. The dot notation acts like a path leading to the desired property within the object.[]) provides an alternative way to access properties, especially useful when the property name is a variable or contains special characters.
const person = {
"first name": "Alice", // Property name with space (use square brackets)
lastName: "Smith",
age: 30
};
const propertyName = "age";
const age = person[propertyName];
console.log(age); // Output: 30
firstName property has a space in its name. Dot notation wouldn’t work in this case.
const student = {
name: "Bob",
grades: {
math: 85,
science: 90
}
};
const mathGrade = student.grades.math;
console.log(mathGrade); // Output: 85
student object with a nested object named grades containing math and science grades.math grade, we chain the property accesses: student.grades.math. This follows the path from the student object to the nested grades object and then retrieves the math property within it.hasOwnProperty() MethodhasOwnProperty() method is a built-in function that determines whether an object has a specific property as its own (not inherited from its prototype).
const person = {
firstName: "Alice"
};
person.__proto__.lastName = "Smith"; // Add lastName to prototype
console.log(person.hasOwnProperty("lastName")); // Output: false (not own property)
console.log(person.lastName); // Output: Smith (inherited)
person object with firstName.lastName property to the prototype chain using person.__proto__.lastName. This property isn’t directly defined on person.person.hasOwnProperty("lastName") returns false because lastName isn’t an own property of person. However, we can still access the inherited value using person.lastName.
const person = {
firstName: "Alice",
lastName: "Smith"
};
const { firstName, lastName } = person;
console.log(firstName, lastName); // Output: Alice Smith
firstName and lastName properties from the person object.{} enclose the properties we want to extract.firstName and lastName on the left side receive the corresponding values from the object.By mastering these techniques, you can effectively access and manipulate object properties in JavaScript, unlocking the power of these versatile data structures. Remember to choose the appropriate method based on the property names and your coding style preferences. Happy coding !❤️
