Js Object Properties in JavaScript
? JavaScript Object Properties
In JavaScript, object properties are key-value pairs that define the characteristics and data of an object. They are fundamental to how objects work.
?? Declaring Object Properties
let person = { firstName: "Alice", lastName: "Johnson", age: 30};firstName,lastName, andageare property keys"Alice","Johnson", and30are the property values
? Accessing Properties
Dot Notation
console.log(person.firstName); // "Alice"Bracket Notation (useful for dynamic or invalid keys)
console.log(person["lastName"]); // "Johnson"let key = "age";console.log(person[key]); // 30? Modifying Properties
person.age = 31;person["firstName"] = "Eve";? Adding New Properties
person.email = "eve@example.com";? Deleting Properties
delete person.lastName;? Check If Property Exists
"age" in person; // trueperson.hasOwnProperty("email"); // true? Looping Through Properties
for (let key in person) { console.log(key + ": " + person[key]);}? Property Names
Can be strings or symbols
If a property name has spaces or special characters, use quotes:
let obj = { "full name": "Alice Johnson" };console.log(obj["full name"]); // "Alice Johnson"?? Object.defineProperty()
Advanced way to define a property with specific attributes:
let user = {};Object.defineProperty(user, "id", { value: 101, writable: false, enumerable: true});console.log(user.id); // 101user.id = 202; // won't change because writable is false? Summary
Object properties are key-value pairs.
Access with dot or bracket notation.
Modify, add, delete, and loop through them easily.
Use
hasOwnProperty()orinto check existence.Use
defineProperty()for detailed control.
Would you like an example that builds a dynamic object from user input or JSON?