JavaScript Objects – Properties, Methods and Destructuring
Quick Answer: A JavaScript object stores related information together. Properties hold values, methods define actions, and destructuring extracts selected values into variables. These features help us organise data and write cleaner JavaScript.
1. Why Do We Need JavaScript Objects?
Imagine you manage an online grocery shop. You receive hundreds of customer orders every day. How will you store each order's details?
Think about it for a moment.
The Problem: Storing Order Details Without Objects
We could create separate variables for every order. This works for a small number of orders.
Example 1: Store Three Grocery Orders Without Objects
Each order needs a customer, item and amount.
const customer1 = "Priya";
const item1 = "Rice";
const amount1 = 1200;
const customer2 = "Ravi";
const item2 = "Cooking Oil";
const amount2 = 850;
const customer3 = "Lakshmi";
const item3 = "Wheat Flour";
const amount3 = 450;
console.log(customer1, item1, amount1);
console.log(customer2, item2, amount2);
console.log(customer3, item3, amount3);
Expected output
Priya Rice 1200 Ravi Cooking Oil 850 Lakshmi Wheat Flour 450
Note: This works, but it gets hard to manage.
What Goes Wrong as Orders Increase?
- Related information is stored in separate variables.
- Adding another order means creating more variables.
- Passing complete order details to a function becomes difficult.
- Updating the code becomes harder as the order count grows.
- Calculating totals requires repeated logic.
Now imagine managing 1,000 customer orders. We need a better structure.
2. The Solution: Create Objects
Object = a single structure that groups related data and actions.
We can represent each grocery order as one object. Its details stay together.
Example 2: Create Grocery Order Objects
This example stores order details and calculates the final amount.
const order1 = {
orderId: "ORD101",
customer: "Priya",
item: "Rice",
quantity: 2,
price: 600,
calculateTotal() {
return this.quantity * this.price;
},
showSummary() {
console.log(`Order: ${this.orderId}`);
console.log(`Customer: ${this.customer}`);
console.log(`Item: ${this.item}`);
console.log(`Total: ₹${this.calculateTotal()}`);
}
};
order1.showSummary();
Expected output
Order: ORD101 Customer: Priya Item: Rice Total: ₹1200
One object now holds the complete order. We can also create more orders using the same structure.
3. Understand the Object Structure
A JavaScript object contains properties and can also contain methods.
- Property = a named value stored inside an object.
- Method = a function stored inside an object.
- Key = the name used to access a property or method.
- Value = the data assigned to a key.
this= refers to the object used for the current method call.
How an Object Holds Order Information
The order object groups its stored values and available actions in one place.
Access Object Properties
We can access properties using dot notation or bracket notation.
Example 3: Read and Update Object Properties
console.log(order1.customer);
console.log(order1["item"]);
order1.quantity = 3;
order1.status = "Confirmed";
console.log(order1.quantity);
console.log(order1.status);
Expected output
Priya Rice 3 Confirmed
- Dot notation uses the property name directly.
- Bracket notation uses a string or variable as the key.
- Assignment changes an existing property value.
- Assignment can also add a new property.
Remember: Use bracket notation when the property name is dynamic or contains special characters.
4. JavaScript Object Methods
Method = a function that belongs to an object.
Methods help an object perform actions using its own data.
Our grocery order has two methods:
calculateTotal()calculates the order amount.showSummary()prints the order details.
How Does a Method Use this?
The this keyword refers to the object before the method call.
For example, order1.calculateTotal() uses order1 as its current object.
Example 4: Calculate an Order Total Using this
const order = {
customer: "Ravi",
quantity: 4,
price: 250,
calculateTotal() {
return this.quantity * this.price;
}
};
console.log(order.calculateTotal());
Expected output
1000
Important: Regular Methods and Arrow Functions
Regular methods receive this from their call site. Arrow functions do not create their own this.
For object methods that use object properties, a concise method is usually clear.
Example 5: Avoid an Arrow Function for this-Based Object Methods
const orderDetails = {
customer: "Lakshmi",
showCustomer() {
return this.customer;
}
};
console.log(orderDetails.showCustomer());
Expected output
Lakshmi
Common mistake: Do not replace a regular method with an arrow function when it needs its own this.
5. JavaScript Object Destructuring
Destructuring = taking selected values from an object into variables.
It helps us avoid repeating long property access expressions.
Imagine we only need the customer name and order amount. We do not need to copy the complete object.
Example 6: Extract Properties Using Destructuring
const groceryOrder = {
orderId: "ORD202",
customer: "Priya",
item: "Rice",
amount: 1200
};
const { customer, amount } = groceryOrder;
console.log(customer);
console.log(amount);
Expected output
Priya 1200
The variable names match the property names. JavaScript assigns the matching values automatically.
Rename Variables During Destructuring
Sometimes we want a different variable name. We can use an alias.
Example 7: Rename an Object Property
const { customer: customerName } = groceryOrder;
console.log(customerName);
Expected output
Priya
customer is the property name. customerName is the new variable name.
Set Default Values
A default value is used when the property is missing or undefined.
Example 8: Use a Default Value
const { deliveryStatus = "Pending" } = groceryOrder;
console.log(deliveryStatus);
Expected output
Pending
Important: A default value applies to undefined. It does not replace null.
Nested Object Destructuring
Objects can contain other objects. We can extract values from nested objects too.
Example 9: Extract a Nested Delivery Address
const orderWithAddress = {
orderId: "ORD303",
customer: "Ravi",
delivery: {
city: "Ballari",
pincode: "583101"
}
};
const {
delivery: { city, pincode }
} = orderWithAddress;
console.log(city);
console.log(pincode);
Expected output
Ballari 583101
Nested destructuring follows the object's structure. The nested property must exist unless we provide a safe default.
Rest Properties in Destructuring
The rest syntax collects remaining properties into a new object.
Example 10: Extract Selected Values and Keep the Rest
const {
customer: name,
...otherDetails
} = groceryOrder;
console.log(name);
console.log(otherDetails);
Expected output
Priya
{ orderId: 'ORD202', item: 'Rice', amount: 1200 }
The rest variable contains the properties that were not extracted earlier.
6. Follow the Data Through Destructuring
Destructuring reads selected properties from an existing object. It does not remove those properties.
The object supplies selected values to variables while keeping its original properties.
7. Objects vs Properties vs Methods vs Destructuring
| Concept | Meaning | Grocery order example |
|---|---|---|
| Object | Groups related data and actions. | groceryOrder |
| Property | Stores a value. | customer: "Priya" |
| Method | Performs an action. | calculateTotal() |
| Destructuring | Extracts selected values. | const { customer } = groceryOrder |
8. Common Mistakes and Best Practices
Mistake 1: Accessing a Missing Property
Reading a missing property returns undefined. Check optional data before using nested properties.
Safer Access with Optional Chaining
const city = orderWithAddress.delivery?.city;
console.log(city);
Expected output
Ballari
Mistake 2: Forgetting the this Context
A method can lose its expected this when passed separately.
Call the method through its object, or bind the required context.
Mistake 3: Destructuring a Missing Nested Object
Direct nested destructuring fails when the parent property is undefined.
Use a Default Object for Optional Nested Data
const deliveryDetails = orderWithAddress.delivery || {};
const { city: deliveryCity = "Not provided" } = deliveryDetails;
console.log(deliveryCity);
Expected output
Ballari
Mistake 4: Assuming Destructuring Creates a Live Link
Destructuring a primitive property copies its current value into a variable. Later changes to the object's property do not update that variable.
Mistake 5: Mutating Objects Without Intention
Objects can be changed after creation. Use const to protect the variable binding, not the object's contents.
Use Object.freeze() for shallow protection when needed. Nested objects need separate handling.
9. Interview Questions and Answers
1. What is an object in JavaScript?
An object groups related information using key-value pairs. For example, a grocery order stores its customer, item and amount together. It can also contain methods that work with those values.
2. What is the difference between a property and a method?
A property stores information, while a method performs an action. In our order, customer is a property. calculateTotal() is a method.
3. What is object destructuring?
Destructuring extracts selected properties into variables. It makes code shorter and easier to read. We can also rename variables and provide default values.
4. What does this refer to inside an object method?
For a regular method call, this usually refers to the object before the dot. Our order1.calculateTotal() method uses order1 as its context. Detached calls can behave differently.
5. Does destructuring change the original object?
No. Destructuring reads values and assigns them to variables. The original object keeps its properties unless we change them separately.
10. Hands-On Practice
Beginner
- Create a
studentobject with name, course and marks. - Print each property using dot notation.
- Update the student's marks and print the new value.
Intermediate
- Create a grocery order with quantity and price properties.
- Add a
calculateTotal()method. - Extract the customer and total using destructuring.
Advanced
- Add a nested delivery address to the order.
- Use nested destructuring with a default value.
- Use rest properties to collect the remaining order details.
11. Next Steps
You now understand JavaScript objects, properties, methods and destructuring. Practice these features with real application data. They are useful when working with APIs, forms and application state.
Next, explore how arrays and objects work together in JavaScript applications. Keep practising, and share your approach with the Upgradix learning community.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.