JavaScript Object Properties
Object properties store data or methods in key-value form. JavaScript also supports property descriptors to control enumerability, configurability, and writability of properties.
Key Topics
- Defining Properties
- Property Descriptors
- Enumerable, Configurable, Writable
- JavaScript Usage in DOM
- Key Takeaways
Defining Properties
Properties can be defined directly in object literals or via Object.defineProperty()
for advanced options.
let user = {
name: "Alice",
age: 25
};
console.log(user.age);
Output
> 25
Explanation: The object user
has properties name
and age
. Access them via dot notation.
Property Descriptors
Object.defineProperty()
allows configuring properties with descriptors like value
, enumerable
, writable
, configurable
.
Object.defineProperty(user, "location", {
value: "USA",
writable: false,
enumerable: true,
configurable: true
});
console.log(user.location);
user.location = "Canada";
console.log(user.location);
Output
> USA
> USA
Explanation: Because writable
is false, location
cannot be reassigned. Attempts to change it fail silently (or throw in strict mode).
Enumerable, Configurable, Writable
- enumerable: Whether the property shows up in for...in
loops.
- configurable: Whether the property can be redefined or deleted.
- writable: Whether the property value can be changed once set.
JavaScript Usage in DOM
Below is a complete DOM example demonstrating property definitions and descriptors.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Properties in DOM</title>
</head>
<body>
<h1>Object Properties Demo</h1>
<button onclick="lockProperty()">Lock Property</button>
<p id="result"></p>
<script>
let config = {
appName: "MyApp",
version: "1.0"
};
function lockProperty() {
Object.defineProperty(config, "appName", {
value: config.appName,
writable: false,
enumerable: true,
configurable: false
});
config.appName = "NewName";
document.getElementById("result").textContent = "appName: " + config.appName;
}
</script>
</body>
</html>
Key Takeaways
- Basic Properties: Directly define in object literals or
Object.defineProperty()
. - Descriptors: Control enumerability, configurability, and writability.
- DOM Integration: Manage app config or UI object properties safely in larger apps.