JavaScript Object Properties
Object properties in JavaScript store values associated with a key. These key-value pairs define the characteristics of an object, allowing you to structure and manage data efficiently.
Key Topics
- Defining Properties
- Accessing Properties
- Updating and Deleting Properties
- JavaScript Usage in DOM
- Key Takeaways
Defining Properties
Properties are defined as key-value pairs inside an object literal. Keys are typically strings, and values can be any valid data type.
let car = {
brand: "Toyota",
model: "Corolla",
year: 2020
};
console.log(car);
Output
> { brand: "Toyota", model: "Corolla", year: 2020 }
Explanation: The car
object has three properties: brand
, model
, and year
. Printing car
logs the entire object.
Accessing Properties
Properties can be accessed using dot notation or bracket notation. Both methods return the associated value.
console.log(car.brand);
console.log(car["model"]);
Output
> Toyota
> Corolla
Explanation: Using dot notation returns car.brand
, and bracket notation returns car["model"]
, both providing easy access to property values.
Updating and Deleting Properties
You can update property values by assigning a new value and remove properties using the delete
keyword.
car.year = 2021;
delete car.model;
console.log(car);
Output
> { brand: "Toyota", year: 2021 }
Explanation: The year
property is updated to 2021
, and the model
property is removed from the car
object.
JavaScript Usage in DOM
This DOM-based example shows how object properties can store data and how you can display them dynamically on a webpage.
<!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="showCar()">Show Car</button>
<p id="info"></p>
<script>
function showCar() {
let car = { brand: "Honda", model: "Civic", year: 2019 };
document.getElementById("info").textContent = car.brand + " " + car.model + " (" + car.year + ")";
}
</script>
</body>
</html>
Key Takeaways
- Definition: Object properties store key-value pairs for structured data.
- Access: Use dot or bracket notation to retrieve property values.
- Modification: Update or remove properties to keep data relevant.
- DOM Integration: Dynamically display object property values in the browser.