Working with Objects
Learn how to create and work with JavaScript objects through these simple examples.
1. Basic Object Creation
// Create a simple object
let person = {
name: "John",
age: 25,
city: "New York"
};
2. Object Methods
// Object with methods
let calculator = {
add: function(a, b) { return a + b; },
subtract: function(a, b) { return a - b; }
};
3. Object Properties
// Access and modify properties
let car = {
brand: "Toyota",
model: "Camry",
year: 2023
};
console.log(car.brand); // Using dot notation
console.log(car["model"]); // Using bracket notation
4. Nested Objects
// Object containing objects
let school = {
name: "High School",
classes: {
math: { teacher: "Mrs. Smith", students: 25 },
science: { teacher: "Mr. Jones", students: 30 }
}
};
Object Syntax and Methods
Object Creation
// Object Literal Notation
let person = {
name: "John",
age: 30,
city: "New York"
};
// Using Object Constructor
let car = new Object();
car.brand = "Toyota";
car.model = "Camry";
// Object with Methods
let calculator = {
add: function(a, b) {
return a + b;
},
// Shorthand method syntax
subtract(a, b) {
return a - b;
}
};
Accessing Properties
// Dot Notation
console.log(person.name);
// Bracket Notation
console.log(person["age"]);
// Dynamic Property Access
let propertyName = "city";
console.log(person[propertyName]);
// Object Methods
Object.keys(person); // Get all keys
Object.values(person); // Get all values
Object.entries(person); // Get key-value pairs
Advanced Object Concepts
// Object Destructuring
let { name, age } = person;
// Spread Operator
let clone = { ...person };
// Object.defineProperty
Object.defineProperty(person, 'id', {
value: 1,
writable: false,
enumerable: true
});
// Computed Properties
let prefix = "user";
let user = {
[`${prefix}_id`]: 1,
[`${prefix}_name`]: "John"
};
Practice Exercises
Exercise 1: Student Management
Create an object to manage student information:
- Store student details (name, age, grades)
- Add methods to calculate average grade
- Add method to display student info
// Your solution here
let student = {
name: "John Smith",
age: 20,
grades: [85, 90, 92, 88, 87],
calculateAverage() {
let sum = this.grades.reduce((a, b) => a + b, 0);
return sum / this.grades.length;
},
displayInfo() {
return `${this.name}, age ${this.age}
Average Grade: ${this.calculateAverage()}`;
}
};
Exercise 2: Product Catalog
Create a nested object structure for a product catalog:
- Categories with products
- Product details (name, price, stock)
- Methods to update stock and price
// Your solution here
let catalog = {
electronics: {
products: [
{ id: 1, name: "Laptop", price: 999, stock: 5 },
{ id: 2, name: "Phone", price: 699, stock: 10 }
],
updateStock(id, newStock) {
let product = this.products.find(p => p.id === id);
if (product) product.stock = newStock;
},
updatePrice(id, newPrice) {
let product = this.products.find(p => p.id === id);
if (product) product.price = newPrice;
}
}
};