We use assignment to both create and update property values in objects. For non-existing properties, it'll write a new element, for existing properties, it'll overwrite it with the new value:
const user = { name: 'John', married: true, age: 25 };
user.married = false;
// The same
// user['married'] = false;
user.surname = 'Smitt';
// The same
// user['surname'] = 'Smitt';
console.log(user);
// => { name: 'John', married: false, age: 25, surname: 'Smitt' }
Even though the object is declared as a constant, it can change. The reason for this behavior is exactly the same as with arrays. It is not the object itself that is stored in the constant, but a reference to it. This means that you can change the object, but you cannot replace the object with another one:
const user = { name: 'Linda' };
user.name = 'Samuel';
// An error will occur
user = { name: 'Mike' }; // Boom!
You can learn more about this in a future lesson.
Objects being changeable means you can change them step by step. I.e., we can create an empty object and then add to it the desired properties:
const course = {};
course.name = 'Hexlet – JS: Objects';
course.description = 'The coolest course ever, don\'t miss out on it, kids!';
console.log(course.name); // 'Hexlet – JS: Objects'
console.log(course);
// {
// name: 'Hexlet – JS: Objects',
// description: 'The coolest course ever, don\'t miss out on it, kids!'
// }
You can delete an element from an object using the delete
operator:
const user = { name: 'John', wrongProp: 'bug' };
delete user.wrongProp;
console.log(user);
// => { name: 'John' }
Despite the existence of the delete operator, it's bad practice to remove properties from an object. As you'll see later, any problem can be solved without deleting things and, more importantly, code without a delete
operator is better.
https://repl.it/@hexlet/js-objects-syntax-add-update-delete-values-en
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.