Topic 9: JavaScript Object
📖 13 min read · 🎯 Advanced · 🧭 Prerequisites: using-libraries-in-php, data-base-structuring-table-designing
Why this matters
Here's the thing — when you write your first few lines of JavaScript, you store things one by one: a name here, an age there, a city in another variable. That works for a minute. But the moment you want to talk about a person — someone with a name, an age, a city, and maybe a job — you need a way to group all of that together. That's exactly what a JavaScript object does. It lets you bundle related information under one roof, the way the real world actually works. Once you get this, your code stops feeling like a scattered list and starts feeling like something alive.
What You'll Learn
- Create JavaScript objects using three distinct syntaxes: literal,
new Object(), and constructor functions - Read and modify properties with both dot notation and bracket notation
- Add methods to objects and loop over properties with
for...in - Build nested objects and use destructuring to unpack values cleanly
- Apply these techniques in a practical book-collection manager
The Analogy
Think of a JavaScript object as a filing cabinet drawer labelled with a person's name. Each folder inside (a property) holds a specific piece of information — birth date, home address, phone number. Some folders don't hold paper at all; they hold a laminated instruction card (a method) that tells you what to do with the information in the other folders, like "call this person" or "format their address for an envelope." You can add new folders whenever you like, remove ones you no longer need, and even slip an entire second filing cabinet inside one of the folders when the data gets complex enough to warrant it.
Chapter 1: What Is an Object?
In JavaScript, an object is a collection of related data and functionality stored together under one name. The two building blocks are:
- Properties — variables that belong to an object (name, age, city)
- Methods — functions that belong to an object and operate on its properties
Creating an Object — Three Ways
Object Literal Syntax (most common; write properties directly between {})
let person = {
name: "Alice",
age: 25,
city: "Vizag"
};
new Object() Syntax (verbose; assign properties one by one after creation)
let person = new Object();
person.name = "Alice";
person.age = 25;
person.city = "Vizag";
Constructor Function (a blueprint for creating many objects of the same shape)
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
let person = new Person("Alice", 25, "Vizag");
When you call a constructor with new, JavaScript creates a fresh empty object, binds this to it, runs the function body, and returns the result automatically.
Chapter 2: Accessing Object Properties
There are two notations for reading (and writing) properties.
Dot Notation
let person = {
name: "Alice",
age: 25,
city: "Vizag"
};
console.log(person.name); // Output: Alice
console.log(person.age); // Output: 25
Bracket Notation
console.log(person["name"]); // Output: Alice
console.log(person["age"]); // Output: 25
Bracket notation shines when the property key is stored in a variable or contains special characters. Both notations support writing too:
// Modifying properties
person.age = 26;
console.log(person.age); // Output: 26
person["city"] = "CoderTown";
console.log(person.city); // Output: CoderTown
Chapter 3: Adding and Deleting Properties
Objects are dynamic — you can grow or shrink them at any point after creation.
Adding Properties
person.country = "Wonderland";
console.log(person.country); // Output: Wonderland
Assign to a key that doesn't exist yet and JavaScript creates it on the spot.
Deleting Properties
delete person.city;
console.log(person.city); // Output: undefined
The delete operator removes the key entirely; accessing it afterwards yields undefined.
Chapter 4: Object Methods
Methods are functions stored as property values. Inside a method, this refers to the object that owns the method — the key to reading or transforming the object's own data.
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
You can also use ES6 shorthand method syntax (greet() { ... }) which is functionally identical and slightly cleaner to read.
Chapter 5: Looping Through Object Properties
The for...in loop iterates over every enumerable property key of an object, giving you the key as a string on each pass. Combine it with bracket notation to fetch the value.
for (let key in person) {
console.log(key + ": " + person[key]);
}
Sample output (order is insertion order for string keys):
name: Alice
age: 25
city: Vizag
greet: function() { ... }
Tip: if you only want own properties (not inherited ones), guard the loop body with
if (person.hasOwnProperty(key)).
Chapter 6: Nested Objects
A property value can itself be an object, creating as many levels of nesting as your data demands.
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 (or bracket notation) to drill down through each level. You can nest objects arbitrarily deep, though keeping nesting shallow makes code easier to reason about.
Chapter 7: Object Destructuring
Destructuring lets you pull named properties out of an object into standalone variables in a single, readable line.
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 exactly (unless you use the rename syntax: let { name: fullName } = person). Destructuring is especially useful in function parameters to avoid repeatedly writing options.timeout, options.retries, etc.
Chapter 8: Practical Example — Managing a Book Collection
The class brought everything together by modelling a real-world scenario: a collection of books, each represented as an object, stored in an array.
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 output:
JavaScript: The Good Parts by Douglas Crockford (2008)
Eloquent JavaScript by Marijn Haverbeke (2018)
You Don't Know JS by Kyle Simpson (2015)
Key patterns demonstrated here:
- An array of objects is the standard way to manage a list of records in JavaScript
Array.push()appends a new object without replacing the existing collectionArray.forEach()iterates cleanly over each object, giving you the full object on every pass
graph TD
A[bookCollection Array] --> B[book1: The Good Parts]
A --> C[book2: Eloquent JavaScript]
A --> D[book3: You Don't Know JS]
B --> B1[title, author, year]
C --> C1[title, author, year]
D --> D1[title, author, year]
🧪 Try It Yourself
Task: Build a student registry using an array of objects.
- Create three student objects, each with
name,grade(a number 0–100), andsubjectproperties. - Push all three into a
studentsarray. - Loop through the array with
forEachand print each student's name and whether they passed (grade ≥ 50).
Starter snippet:
let students = [];
let s1 = { name: "Ravi", grade: 72, subject: "JavaScript" };
let s2 = { name: "Priya", grade: 45, subject: "PHP" };
let s3 = { name: "Leo", grade: 88, subject: "CSS" };
students.push(s1, s2, s3);
students.forEach(student => {
let status = student.grade >= 50 ? "PASSED" : "FAILED";
console.log(student.name + " — " + status);
});
Success criterion: You should see three lines in the console, each with a student name followed by PASSED or FAILED. Adjust a grade below 50 to verify the failing branch prints correctly.
🔍 Checkpoint Quiz
Q1. What is the difference between a property and a method in a JavaScript object?
A) Properties are read-only; methods can be written
B) Properties store data values; methods store functions that operate on the object
C) Methods are inherited; properties are always own
D) There is no difference — both are just key-value pairs
Q2. Given the following code, what does the last console.log print?
let car = { make: "Toyota", year: 2020 };
delete car.year;
car.color = "blue";
console.log(car.year + " " + car.color);
A) 2020 blue
B) undefined blue
C) NaN blue
D) A ReferenceError is thrown
Q3. What will the following snippet output?
let config = {
host: "localhost",
port: 3306,
db: "example"
};
let { host, db } = config;
console.log(host + "/" + db);
A) undefined/undefined
B) localhost/3306
C) localhost/example
D) host/db
Q4. You have an array of product objects. Each product has name and price. How would you use forEach to print only products that cost more than 100?
A1. B — Properties hold data (strings, numbers, booleans, etc.); methods hold functions that can read or transform the object's own data via this.
A2. B — delete car.year removes the key, so car.year evaluates to undefined. String concatenation with undefined produces "undefined blue".
A3. C — Destructuring extracts host as "localhost" and db as "example", so the output is "localhost/example".
A4.
products.forEach(product => {
if (product.price > 100) {
console.log(product.name + ": $" + product.price);
}
});
Inside forEach, each element is one product object. The if guard filters by price before printing.
🪞 Recap
- A JavaScript object groups related properties (data) and methods (behaviour) under one name.
- Objects can be created three ways: literal
{},new Object(), or a constructor function — literal syntax is the most common. - Use dot notation for known keys and bracket notation when the key is dynamic or stored in a variable.
- The
deleteoperator removes a property entirely; assigning to a new key adds it on the fly. - Nested objects and arrays of objects let you model arbitrarily complex real-world data structures.
- Object destructuring (
let { name, age } = person) unpacks properties into variables cleanly in one line.
📚 Further Reading
- MDN: Working with Objects — the source of truth on JS object syntax and behaviour
- MDN: Destructuring Assignment — full reference on object and array destructuring syntax
- Eloquent JavaScript — Chapter 4: Data Structures — Marijn Haverbeke's free deep-dive into objects and arrays
- ⬅️ Previous: Data Base Structuring, Table Designing
- ➡️ Next: Using Other Open-Source Material