JavaScript Objects

Objects in JavaScript are collections of key-value pairs. They allow you to group related data and functions, making it easier to structure and manage complex information.

Key Topics

Creating Objects

Objects can be created using object literals, constructors, or the new keyword. The most common way is with an object literal.

let person = {
    name: "Alice",
    age: 25
};
console.log(person);

Output

> { name: "Alice", age: 25 }

Explanation: The person object stores two properties: name and age. Printing the object logs its key-value pairs to the console.

Accessing Properties

Object properties can be accessed using dot notation or bracket notation.

console.log(person.name);    // Using dot notation
console.log(person["age"]);  // Using bracket notation

Output

> Alice

> 25

Explanation: The person object's name and age properties are retrieved using different notations. Both methods yield the same result.

Adding and Modifying Properties

You can add new properties or modify existing ones by assigning values to object properties.

person.location = "New York";
person.age = 26;
console.log(person);

Output

> { name: "Alice", age: 26, location: "New York" }

Explanation: A new property location is added to the person object, and the age property is updated. The updated object is logged to the console.

JavaScript Usage in DOM

This DOM-based example demonstrates how objects can store data and then be used to dynamically update page content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Objects in DOM</title>
</head>
<body>
    <h1>Object Demo</h1>
    <button onclick="showPerson()">Show Person</button>
    <p id="info"></p>

    <script>
        function showPerson() {
            let user = {
                name: "Bob",
                role: "Developer"
            };
            document.getElementById("info").textContent = user.name + " is a " + user.role;
        }
    </script>
</body>
</html>

Key Takeaways

  • Object Creation: Use object literals to define key-value pairs.
  • Accessing Properties: Dot and bracket notation retrieve object values.
  • Modifying Properties: Add or update properties to manage dynamic data.
  • DOM Integration: Leverage objects to store and display data on webpages.