Object Properties in JavaScript
Object Properties in JavaScript
What Are Object Properties?
Properties are key-value pairs associated with JavaScript objects.
Each property has:
A key (also called name)
A value (can be any data type)
Properties define the characteristics or data of an object.
Defining Properties
const person = { name: "Alice", // key: name, value: "Alice" age: 30, isStudent: false};Accessing Properties
Dot Notation
console.log(person.name); // AliceBracket Notation
console.log(person["age"]); // 30Useful when property names are dynamic or not valid identifiers.
Adding or Modifying Properties
person.city = "New York"; // Add new propertyperson["country"] = "USA"; // Another way to addperson.age = 31; // Modify existing propertyDeleting Properties
delete person.isStudent;console.log(person.isStudent); // undefinedProperty Attributes (Advanced)
Properties have internal attributes:
| Attribute | Description |
|---|---|
value | The property's value |
writable | Can the property's value be changed? |
enumerable | Shows up in loops like for...in? |
configurable | Can property be deleted or changed? |
You can check or define these using:
Object.getOwnPropertyDescriptor(person, "name");Object.defineProperty(person, "name", { writable: false });Checking if Property Exists
"name" in person; // trueperson.hasOwnProperty("age"); // trueSummary
| Operation | Syntax Example |
|---|---|
| Define property | obj.key = value or obj["key"] = value |
| Access property | obj.key or obj["key"] |
| Delete property | delete obj.key |
| Check existence | "key" in obj or obj.hasOwnProperty("key") |
Want me to explain property descriptors or show how to iterate properties?