JavaScript Tutorial 5: Objects & Data Structures

Lesson 4 Review

In our last lesson, we learned how to use Arrays to store long lists of data, like let colors = ["red", "blue", "green"]. However, Arrays are only good for identical types of data. What if you want to store a specific User's Name, Age, Email, and Subscription Status all in one place? For complex, grouped data, we use Objects.

Step 1: The Object Literal (Keys and Values)

An Object in JavaScript is a standalone entity, with properties and types. Compare it to a real-world object, like a car. A car has properties: a color, a brand, a weight, and a model year.

In JavaScript, we create objects using curly braces { }. Inside the braces, we write data in Key-Value Pairs. The "Key" is the name of the property, and the "Value" is the data itself.

The JavaScript: Creating an Object

const userProfile = {
  firstName: "Poorna", // String
  lastName: "Prasad", // String
  age: 23, // Number
  isStudent: true, // Boolean
  skills: ["HTML", "CSS", "JS"] // You can even put Arrays inside Objects!
};
Syntax Rules: Notice that inside an object, we use a colon : to separate the key from the value, NOT an equals sign. And we separate each pair with a comma ,.

Step 2: Accessing and Modifying Object Data

Once you have built an object, you need to extract the data to use it in your webpage. There are two ways to do this: Dot Notation and Bracket Notation.

Dot Notation (The Standard Way)

This is the cleanest and most common way to read or change data inside an object. You simply type the object's name, a dot, and the key.

The HTML & JavaScript: Dynamic Profile Card

<!-- HTML -->
<div id="profile-card" style="border: 2px solid #333; padding: 15px;">
  <h2 id="name-display"></h2>
  <p id="role-display"></p>
</div>

/* JavaScript */
const employee = {
  name: "Alice Engineer",
  role: "Junior Developer"
};

// 1. Reading Data using Dot Notation
document.getElementById("name-display").innerHTML = employee.name;

// 2. Modifying Data (Promoting the employee)
employee.role = "Senior Developer";
document.getElementById("role-display").innerHTML = "Title: " + employee.role;

The Output:

Alice Engineer

Title: Senior Developer

Bracket Notation (The Dynamic Way)

You use bracket notation ["key"] when the key name has a space in it (which is bad practice anyway), or when you are using a variable to look up the key.

let searchQuery = "age";
console.log( userProfile[searchQuery] ); // Uses the variable to look up "age". Outputs: 23

Step 3: Object Methods & The 'this' Keyword

Objects don't just hold static data. They can also hold functions! When a function is placed directly inside an object, it is called a Method. This is how you make objects actually *do* things.

Inside a method, you often need to access the object's own data. To do this, you must use the this keyword. this acts as a mirror, pointing back to the object itself.

The JavaScript: Making an Object Speak

const smartHome = {
  temperature: 72,
  systemStatus: "Active",

  // This is a Method (a function inside an object)
  printReport: function() {
    // We MUST use 'this.' to access properties from inside the object
    return "System is " + this.systemStatus + ". Temp is " + this.temperature + " degrees.";
  }
};

// Calling the method
console.log( smartHome.printReport() );
Common Beginner Bug: If you write return "Temp is " + temperature; without using this., JavaScript will crash, saying "temperature is not defined." It will look outside the object in the global scope instead of looking inside itself!

Step 4: Arrays of Objects (The Core of Web Dev)

This is the most important architectural pattern in Modern Web Development. When you fetch data from a database or an API (like pulling a list of videos from YouTube), the data arrives as an Array full of Objects.

You then write a Loop (like we learned in Lesson 4) to cycle through the Array, extract the Object data, and generate HTML layout cards dynamically.

The HTML, CSS, & JavaScript: Building a Product Grid

<!-- HTML Container for our Grid -->
<div id="store-front" style="display: flex; gap: 15px;"></div>

/* JavaScript */
// 1. The Database (Array of Objects)
const products = [
  { id: 1, title: "Laptop", price: 999, inStock: true },
  { id: 2, title: "Mouse", price: 25, inStock: true },
  { id: 3, title: "Keyboard", price: 45, inStock: false }
];

let storeHTML = document.getElementById("store-front");

// 2. Loop through the array using forEach
products.forEach( (item) => {
  // 3. Determine button color based on the Object's boolean status
  let statusColor = item.inStock ? "green" : "red"; // Ternary Operator
  let statusText = item.inStock ? "Buy Now" : "Out of Stock";

  // 4. Generate the HTML block using string concatenation
  let card = "<div style='padding:15px; border:1px solid #ccc; border-radius:8px;'>" +
             "<h3 style='margin:0 0 10px 0;'>" + item.title + "</h3>" +
             "<p style='font-size:1.2em; font-weight:bold;'>$" + item.price + "</p>" +
             "<button style='background:" + statusColor + "; color:white; border:none; padding:8px;'>" + statusText + "</button>" +
             "</div>";

  // 5. Append it to the page
  storeHTML.innerHTML += card;
});

The Final Dynamic Output:

Laptop

$999

Mouse

$25

Keyboard

$45

Final Quiz: Test Your Data Structure Logic

Click the buttons below to verify your knowledge.

1. What is the fundamental difference between an Array and an Object?
2. Look at this code: `let user = { name: "Sarah", age: 30 };`. What is the correct syntax to change Sarah's age to 31?
3. Inside an Object Method, why must you use the `this` keyword? (e.g., `this.temperature`)

Post a Comment

0 Comments