JAVASCRIPT

Object Properties


An object property are key-value pairs that define the characteristics or attributes of an object. They can hold various types of data, including primitive data types like strings, numbers, and booleans, as well as more complex data types like arrays, functions, and even other objects.

 

Example:

let employee = {
    name: "Rohit",
    age: 25,
    isStudent: false,
    hobbies: ["reading", "cooking", "traveling"],
    address: {
        street: "3 bypass St",
        city: "Kolkata",
        country: "India"
    },
    greet: function() {
        return "Hello, my name is " + this.name + ".";
    }
};

 

In this example, person is an object with several properties:

1. `name`, `age`, and `isStudent` - primitive properties.
2. ‘hobbies’ - is an array property containing a list of hobbies.
3. `address` - an object property containing nested properties for street, city, and country.
4. `greet` - is a method property, a function attached to the object.
 

 

Accessing Object Properties:

 

Mainly we can access object properties in two ways:

1. Dot notation: This is the most common way to access properties of an object just by using dot(.) followed by the name of property.

2. Bracket notation: We can also access object properties by using square brackets `[]`. In square brackets, we have to give property name as a string.

 

Example:

// Accessing Object property
console.log(person.name); // Output: Rohit
console.log(person["age"]); // Output: 25
console.log(person.address.city); // Output: Kolkata
console.log(person.hobbies[0]); // Output: reading
console.log(person.greet()); // Output: Hello, my name is Rohit.

 

Modifying Object Properties:

 

Mainly we can modify object properties in two ways:

1. Dot notation: This is the most common way to modify properties of an object just by using dot(.) followed by the name of property.

2. Bracket notation: We can also modify object properties by using square brackets `[]`. In square brackets, we have to give property name as a string.

 

Example:

// Modifying Object Property
person.name = "Wasif";
person["age"] = 22;
person.job = "Developer"; // Add new property

 

Note: We can also add object properties.