Understanding JavaScript Objects
Understanding JavaScript Objects
in
5. Deleting Properties
delete person.age;
console.log(person.age); // Output: undefined
6. Object Methods
const personWithFullName = {
firstName: "John",
lastName: "Doe",
getFullName: function() {
return `${this.firstName}
${this.lastName}`;
}
};
console.log(personWithFullName.getFullName()); //
Output: John Doe
7. Nested Objects
const student = {
name: "Bob",
age: 20,
grades: {
math: 90,
science: 85,
english: 88
}
};
8. Object Destructuring
const user = { id: 1, username: "john_doe", email:
"john@example.com" };
const { username, email } = user;
console.log(username, email); // Output: john_doe
john@example.com
10. Object.keys()
const carKeys = Object.keys(car);
console.log(carKeys); // Output: ["make", "model",
"year"]
11. Object.values()
const carValues = Object.values(car);
console.log(carValues); // Output: ["Toyota",
"Camry", 2020]
12. Object.entries()
const carEntries = Object.entries(car);
console.log(carEntries); // Output: [["make",
"Toyota"], ["model", "Camry"], ["year", 2020]]
14. Prototypes
function Animal(type) {
this.type = type;
this.speak = function() {
console.log(`${this.type} makes a sound.`);
};
}
const dog = new Animal("Dog");
dog.speak(); // Output: Dog makes a sound.
15. Inheritance
function Dog(breed) {
Animal.call(this, "Dog"); // Call the parent
constructor
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
const myDog = new Dog("Labrador");
console.log(myDog.type); // Output: Dog
console.log(myDog.breed); // Output: Labrador
myDog.speak(); // Output: Dog makes a sound.
16. Object.freeze()
const frozenObject = Object.freeze({ name: "Alice",
age: 30 });
frozenObject.age = 31; // This will not change the
age property
console.log(frozenObject.age); // Output: 30
17. Object.seal()
const sealedObject = Object.seal({ name: "Bob",
age: 25 });
sealedObject.age = 26; // This will work
sealedObject.city = "New York"; // This will not
work
console.log(sealedObject); // Output: { name:
"Bob", age: 26 }