5.4 Dynamiquc of Objects
A fundamental thing to understand about JavaScript objects is that they are dynamic. Once you have created an object, you can still add new properties or methods to it, or remove existing ones — even at runtime. Starting from a simple object with a single radius property:
const circle = { radius: 1 };
circle.color = "yellow"; // add a property
circle.draw = function () { // add a method
console.log("draw");
};
delete circle.color; // remove a property
delete circle.draw; // remove a method
What about const?
constprevents you from reassigning the variable to a different object —circle = ...would throw "Assignment to constant variable."- It does not freeze the object itself. You can still add, change or delete its properties.
This is a common source of confusion. const makes the binding immutable, not the contents. If you log the circle after the additions, you see two members (radius and color) plus a draw method. After the delete calls, only radius remains — the property we set when we initially created the object.
This dynamic nature is one of the most powerful and flexible aspects of JavaScript. You should always know whether you want a property to exist, and avoid mutating shared objects in unpredictable places. See you in the next video.
Summary
This lesson explains the dynamic nature of JavaScript objects, demonstrating how developers can add new properties and methods to objects after their creation and remove them using the delete operator. It clarifies an important distinction: while const prevents variable reassignment, it does not prevent modification of the object's properties and methods, allowing full manipulation of the object itself.
Key points
- JavaScript objects are dynamic—properties and methods can be added or removed after object creation
- Use the delete operator to remove properties or methods from an object (e.g., delete circle.color)
- const keyword prevents variable reassignment but allows object property and method modification
- Objects maintain flexibility even when declared as constants, enabling extensive customization
FAQ
Can I modify an object that is declared with const?
Yes. The const keyword prevents reassignment of the variable itself, but it does not prevent you from adding, modifying, or deleting the object's properties and methods.
How do I remove a property or method from an object?
Use the delete operator followed by the property or method name. For example: delete circle.color removes the color property, and delete circle.draw removes the draw method.
What does it mean that JavaScript objects are dynamic?
Dynamic objects allow you to add new properties and methods after the object is created, and remove existing ones at any time, providing flexibility to modify object structure during runtime.