In this tutorial, we will learn what are object properties in JavaScript with some cool and easy examples. In many situations, you might have to come up with this type of requirements.
I know you are here just because you are in need of this awesome trick to take in JavaScript, object properties are defined as key-value pairs, where the key represents the property name, and the value denotes its corresponding data. Accessing or modifying properties can be achieved through dot or bracket notation.
JavaScript objects provide a dynamic and flexible structure for data manipulation in web development.
JavaScript Object Properties
const dog = { name: "Rocky", }; //access property console.log(dog.name);
Output:
Rocky
2. Using Bracket Notation
const cat = { name: "Luna", }; // access property console.log(cat["name"]);
JavaScript Object Operations
In JavaScript, we can perform various operations on object properties like modifying, adding, deleting, and so on.
Modify Object Properties
We can modify object properties by assigning a new value to an existing key. For example,
const person = { name: "Bobby", hobby: "Dancing", }; //modify property person.hobby = "Singing"; //display the object console.log(person);
Output:
{name: ‘Bobby’, hobby: ‘Singing’}
//Define an object const person = { firstName: 'John', lastName: 'Doe', age: 30, address: { street: '123 Main St', city: 'New York', zip: '10001' }, hobbies: ['reading', 'gardening', 'traveling'], greet: function () { console.log ('Hello, my name is ${this.firstName} ${this.lastName}.'); } }; //Accessing object properties console.log(person.firstName); // Output: John console.log(person.address.city); // Output: New York console.log(person.hobbies[1]); // Output: gardening //Adding a new property person.email = '[email protected]'; // Updating a property person.age = 32; //delete person.address; //Invoking a method person.greet(); //Output: Hello, my name is John Doe.
An object is a collection of properties, and a property is an association between a name and a value.
How to write JavaScript using eval() function.
How to write a function in JavaScript using eval()function
Difference between throw new Error and throw someObject