JavaScript Objects - Adding and Modifying Properties


Objects are a central data structure in JavaScript, and they allow you to group related data and functions. In this guide, we'll explore how to manipulate objects by adding and modifying properties, and provide examples to illustrate each concept.


Creating Objects


You can create objects using object literals or the new Object() constructor:


// Using object literals
let person = {
firstName: "John",
lastName: "Doe"
};
// Using the Object constructor
let car = new Object();
car.make = "Toyota";
car.model = "Camry";

Adding Properties


You can add properties to objects using dot notation or bracket notation:


// Using dot notation
person.age = 30;
// Using bracket notation
car["year"] = 2022;

Modifying Properties


You can modify existing properties by reassigning their values:


// Modifying properties
person.firstName = "Alice";
car.make = "Honda";

Adding and Modifying Properties with Square Bracket Notation


Square bracket notation is useful when property names contain special characters or when the property name is stored in a variable:


let propertyName = "color";
car[propertyName] = "blue";
person["last name"] = "Smith";
// Modifying properties with square bracket notation
car["year"] = 2023;

Object Methods


Objects can also contain functions as properties, which are called methods:


let calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
// Using object methods
let sum = calculator.add(5, 3);
let difference = calculator.subtract(8, 2);

Conclusion


JavaScript objects are versatile data structures that allow you to organize and manipulate data efficiently. By understanding how to add and modify properties, you can create and modify objects to suit your application's needs.


Happy coding!