Topic 24 of 26 · UI Designer

Topic 9 : JavaScript Object

Lesson TL;DRTopic 9: JavaScript Object 📖 5 min read · 🎯 Advanced · 🧭 Prerequisites: javascriptevents, tagslist Why this matters Here's the thing — when you write code for real apps, data comes in groups. A use...
5 min read·advanced·javascript · objects · data-structures · destructuring

Topic 9: JavaScript Object

📖 5 min read · 🎯 Advanced · 🧭 Prerequisites: javascript-events, tags-list

Why this matters

Here's the thing — when you write code for real apps, data comes in groups. A user isn't just a name. They have a name, an age, an email, a city. Up until now, you'd need four separate variables just to describe one person. That gets messy fast. JavaScript objects solve this by letting you bundle all that related information under one roof — one variable that holds everything. Once you get comfortable with objects, you'll start seeing them everywhere in JavaScript. They're the building blocks of nearly every project you'll ever build.

What You'll Learn

  • Create objects using literal syntax, new Object(), and constructor functions
  • Access and modify object properties using dot and bracket notation
  • Add and delete properties dynamically at runtime
  • Define methods on objects and use this to reference their own properties
  • Loop through object properties with for...in
  • Work with nested objects and complex data structures
  • Destructure objects to extract values into variables
  • Model a real-world collection (books) using an array of objects

The Analogy

Think of a JavaScript object like a city resident's profile card in the Vizag directory. The card itself is the object; each field printed on it — name, address, occupation — is a property. If the card also lists a phone number you can call to reach that resident, that callable entry is a method. You can read any field with a glance (dot notation), flip to a field by its label name (bracket notation), paste a sticker on a blank line to add a new property, or peel a sticker off to delete one. Nested objects are like a card that has a mini-card stapled to it for the resident's home address — structured data inside structured data.

Chapter 1: What Is an Object?

the trainer opened the session: "In JavaScript, an object is a collection of related data and functionalities. Properties are variables that belong to an object; methods are functions that belong to an object."

There are three common ways to create objects:

1. Object Literal Syntax

The most concise and idiomatic approach — wrap key-value pairs in curly braces.

let person = {
    name: "Alice",
    age: 25,
    city: "Vizag"
};

2. Using the new Object() Syntax

Construct an empty object and assign properties one at a time.

let person = new Object();
person.name = "Alice";
person.age = 25;
person.city = "Vizag";

3. Using a Constructor Function

Define a reusable blueprint (like a class before ES6 classes existed) and instantiate it with new.

function Person(name, age, city) {
    this.name = name;
    this.age = age;
    this.city = city;
}
let person = new Person("Alice", 25, "Vizag");

Constructor functions are powerful when you need to stamp out many objects of the same shape.

Chapter 2: Accessing Object Properties

We learned two notations for reading and writing object properties.

Dot Notation

The most readable option when the property name is a valid identifier you know at write-time.

let person = {
    name: "Alice",
    age: 25,
    city: "Vizag"
};

console.log(person.name); // Output: Alice
console.log(person.age);  // Output: 25

Bracket Notation

Required when the property name is dynamic (stored in a variable) or contains special characters.

console.log(person["name"]); // Output: Alice
console.log(person["age"]);  // Output: 25

// Modifying properties
person.age = 26;
console.log(person.age);  // Output: 26

person["city"] = "CoderTown";
console.log(person.city); // Output: CoderTown

Both notations read and write the same underlying property slot — they are interchangeable for valid identifiers.

Chapter 3: Adding and Deleting Properties

the trainer demonstrated that objects in JavaScript are not fixed schemas. You can grow or shrink them at any time.

Adding Properties

Assign to a key that doesn't exist yet and JavaScript creates it on the spot.

person.country = "Wonderland";
console.log(person.country); // Output: Wonderland

Deleting Properties

The delete operator removes a key and its value entirely. After deletion, accessing the key returns undefined.

delete person.city;
console.log(person.city); // Output: undefined

Chapter 4: Object Methods

Methods are functions stored as property values. Inside a method, this refers to the object the method is called on.

let person = {
    name: "Alice",
    age: 25,
    city: "Vizag",
    greet: function() {
        console.log("Hello, my name is " + this.name);
    }
};

person.greet(); // Output: Hello, my name is Alice

this.name resolves to "Alice" because greet is invoked on person. Arrow functions do not bind their own this, so use regular function expressions for methods that need to reference sibling properties.

Chapter 5: Looping Through Object Properties

the trainer introduced the for...in loop, which iterates over all enumerable string-keyed properties of an object.

for (let key in person) {
    console.log(key + ": " + person[key]);
}

Each iteration assigns the next property name to key, then bracket notation retrieves the value. This works whether the object has three properties or thirty.

flowchart TD
    A[Start for...in loop] --> B{More keys?}
    B -- Yes --> C[key = next property name]
    C --> D[Access person\[key\]]
    D --> E[console.log output]
    E --> B
    B -- No --> F[Loop ends]

Chapter 6: Nested Objects

Objects can contain other objects as property values, allowing arbitrarily deep data structures.

let person = {
    name: "Alice",
    age: 25,
    address: {
        street: "123 Main St",
        city: "Vizag",
        country: "Wonderland"
    }
};

console.log(person.address.city); // Output: Vizag

Chain dot notation to drill into nested levels. You can also mix dot and bracket notation: person["address"].city is equally valid.

Chapter 7: Object Destructuring

Destructuring lets you unpack object properties into standalone variables in a single statement — cleaner than repeating person.name, person.age, etc.

let person = {
    name: "Alice",
    age: 25,
    city: "Vizag"
};

let { name, age, city } = person;

console.log(name); // Output: Alice
console.log(age);  // Output: 25
console.log(city); // Output: Vizag

The variable names on the left must match the property keys on the right. You can also rename during destructuring: let { name: fullName } = person; stores the value in fullName.

Chapter 8: Practical Example — Managing a Book Collection

The class put everything together by modeling a real-world collection of books.

let book1 = {
    title: "JavaScript: The Good Parts",
    author: "Douglas Crockford",
    year: 2008
};

let book2 = {
    title: "Eloquent JavaScript",
    author: "Marijn Haverbeke",
    year: 2018
};

let bookCollection = [book1, book2];

// Adding a new book to the collection
let book3 = {
    title: "You Don't Know JS",
    author: "Kyle Simpson",
    year: 2015
};
bookCollection.push(book3);

// Displaying the book collection
bookCollection.forEach(book => {
    console.log(book.title + " by " + book.author + " (" + book.year + ")");
});

Expected console output:

JavaScript: The Good Parts by Douglas Crockford (2008)
Eloquent JavaScript by Marijn Haverbeke (2018)
You Don't Know JS by Kyle Simpson (2015)

Each element in bookCollection is a plain object. forEach iterates the array, and dot notation pulls each property. This pattern — an array of uniform objects — is the foundation for working with API responses, database rows, and virtually every real-world dataset.

🧪 Try It Yourself

Task: Build a studentRoster array that holds at least three student objects, each with name, grade (A–F), and score (0–100). Add a fourth student after the array is created. Then loop through the roster and print each student's name and score. Finally, destructure the first student's object and log a greeting: "Welcome, <name>! Your score is <score>.".

Success criterion: Your console shows four students listed, followed by a personalized greeting for the first student.

Starter snippet:

let student1 = { name: "Bob", grade: "A", score: 95 };
let student2 = { name: "Carol", grade: "B", score: 82 };
let student3 = { name: "Dave", grade: "C", score: 74 };

let studentRoster = [student1, student2, student3];

// TODO: add a fourth student with push()

// TODO: loop and log each student's name and score

// TODO: destructure student1 and log the greeting

🔍 Checkpoint Quiz

Q1. What is the difference between a property and a method on a JavaScript object?

A) A property holds a primitive value; a method holds an object
B) A property is any value stored on an object; a method is a property whose value is a function
C) A method is defined at creation time; a property can be added later
D) There is no difference — they are the same thing

Q2. Given the following code, what does the final console.log print?

let car = { make: "Toyota", year: 2020 };
let key = "year";
car[key] = 2024;
console.log(car.year);

A) 2020
B) undefined
C) "year"
D) 2024

Q3. What is the output of this snippet?

let obj = { a: 1, b: 2, c: 3 };
delete obj.b;
for (let k in obj) {
    console.log(k);
}

A) a, b, c
B) a, c
C) 1, 3
D) a, undefined, c

Q4. You receive an API response object { userId: 42, username: "alice", role: "admin" }. How would you use destructuring to pull out username and role in a single line?

A1. B — A property is any key-value pair on an object. When the value happens to be a function, we call that property a method. The distinction is conceptual, not syntactic.

A2. D — car[key] with key = "year" is equivalent to car["year"], which is the same slot as car.year. Setting it to 2024 overwrites the original 2020.

A3. B — After delete obj.b, the object only has keys a and c. for...in iterates only existing enumerable keys, so b never appears.

A4. let { username, role } = { userId: 42, username: "alice", role: "admin" }; — destructuring extracts only the named keys, ignoring userId entirely.

🪞 Recap

  • An object groups related data (properties) and behavior (methods) under a single identifier.
  • Use dot notation for known property names; bracket notation when the name is dynamic or computed.
  • Properties can be added or removed at any time with simple assignment or the delete operator.
  • The for...in loop iterates over all enumerable keys, and bracket notation retrieves each value.
  • Nested objects model hierarchical data; destructuring extracts properties cleanly into variables.

📚 Further Reading

Like this topic? It’s one of 26 in UI Designer.

Block your seat for ₹2,500 and join the next cohort.