In this lesson, you will learn how to read, update, and remove object properties in JavaScript.
Objects in JavaScript can hold related information. For example, think of a person with a name, age, and profession. This information can be stored in an object:
const person = {
name: 'John',
age: 30,
profession: 'Developer'
};
You can access object properties using dot notation or bracket notation. To get the name of the person, do the following:
console.log(person.name); // Outputs: John
To change a property, you can assign a new value. For example, to update the age:
person.age = 31;
console.log(person.age); // Outputs: 31
You can remove a property using the delete keyword. To remove the profession:
delete person.profession;
console.log(person.profession); // Outputs: undefined
File: objectProperties.js
const person = {
name: 'John',
age: 30,
profession: 'Developer'
};
console.log(person.name); // Outputs: John
person.age = 31;
console.log(person.age); // Outputs: 31
delete person.profession;
console.log(person.profession); // Outputs: undefined
In the example:
person.Create an object called car with properties make, model, and year. Read the properties, update the year, and remove the model property.
const car = {
make: 'Toyota',
model: 'Camry',
year: 2020
};
console.log(car.make);
car.year = 2021;
console.log(car.year);
delete car.model;
console.log(car.model); // Outputs: undefined
undefined. Always check if the property exists.delete keyword: Without it, the property won’t be removed. Make sure to use it correctly.delete keyword.