const obj = { foo: 1 };
obj.bar = 2;
In the given JavaScript example, the obj
object is initially declared with foo: 1
as its property. Later, a new property bar: 2
is added. Thus, the final value of the obj
is { foo: 1, bar: 2 }
.
JavaScript objects are collections of key-value pairs. The keys are always strings or symbols, while the values can be any data type. Properties of JavaScript objects can be accessed, added, or changed at any time after the object is created.
Let's extend the given example to show how this works in practice:
const obj = { foo: 1 }; // initial object declaration
console.log(obj); // will output: { foo: 1 }
obj.bar = 2; // assigning a new property 'bar' with value 2
console.log(obj); // will output: { foo: 1, bar: 2 }
obj.baz = 'Hello, World!'; // assigning a new property 'baz' with string value
console.log(obj); // will output: { foo: 1, bar: 2, baz: 'Hello, World!' }
In this example, we can see how the obj
object changes as we add more properties to it. This signifies the dynamic nature of JavaScript objects.
Adding properties to objects as shown above is a direct way of property assignment and it's very common in JavaScript coding. However, it's critical to manage objects correctly in large codebases to ensure data integrity and avoid bugs.
Object.hasOwnProperty()
method to check if the property exists before assigning a new value, particularly when working with large and complex objects.In conclusion, JavaScript allows the flexibility to add properties to an object after its declaration, leading to the final value of obj
being { foo: 1, bar: 2 }
in the given example.