Object Properties
In JavaScript, an object is a standalone entity, with properties and methods. An object property is a key-value pair, where the key is a string (also called a property name) and the value can be any data type, such as strings, numbers, arrays, and even functions.
object.property
)object['property']
)In JavaScript, we can define an object using the following syntax:
const objectName = { propertyName1: value1, propertyName2: value2, // more properties };
Here, objectName
is the object, and propertyName1
, propertyName2
, etc., are its properties. The values associated with each property can be of any type.
You can access an objectβs properties using two main techniques:
Dot notation is the most common way to access a property of an object.
object.propertyName;
Example:
const person = { name: "Alice", age: 25 };
console.log(person.name); // Output: Alice
Bracket notation allows you to access object properties with a string key, and itβs useful when the property name contains special characters or spaces.
object["propertyName"];
Example:
const person = { name: "Alice", age: 25 };
console.log(person["name"]); // Output: Alice
You can modify the properties of an object by simply reassigning a new value to an existing property.
object.propertyName = newValue;
Example:
const person = { name: "Alice", age: 25 };
person.age = 26;
console.log(person.age); // Output: 26
To remove a property from an object, you can use the delete
operator.
delete object.propertyName;
Example:
const person = { name: "Alice", age: 25 };
delete person.age;
console.log(person.age); // Output: undefined
You can easily add new properties to an object using dot notation or bracket notation.
object.newProperty = value; // Using dot notation object["newProperty"] = value; // Using bracket notation
Example:
const person = { name: "Alice", age: 25 };
person.city = "New York";
console.log(person.city); // Output: New York
Try modifying the object below by changing its properties:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!