Understanding Objects in JavaScript
Introduction
Imagine you have a filing cabinet with labeled drawers. Each drawer has a label (like "Documents", "Photos", "Bills") and contains related items. An object in JavaScript works the same way. It is a container that stores related information with labels (keys) and values.
Arrays are great for storing lists of items, but objects are better for storing related information about a single thing. In this blog, we will learn what objects are, how to create them, and how to work with their properties.
1. What Objects Are and Why They Are Needed
An object is a collection of key-value pairs. Each key is a label, and each value is the data associated with that key.
Why Do We Need Objects?
Objects are perfect for representing things from the real world. Imagine storing information about a student:
Without objects (using multiple variables - messy):
let studentName = "Ashish";
let studentAge = 20;
let studentCity = "Jaipur";
let studentMarks = 450;
let studentCourse = "B.Tech";
console.log(studentName);
console.log(studentAge);
console.log(studentCity);
// This is repetitive and hard to manage!
With objects (clean and organized):
let student = {
name: "Ashish",
age: 20,
city: "Jaipur",
marks: 450,
course: "B.Tech"
};
console.log(student.name);
console.log(student.age);
console.log(student.city);
// Much cleaner and organized!
Objects vs Arrays
Arrays store a list of items in order:
let fruits = ["Apple", "Banana", "Mango"];
// Order matters: first item, second item, third item
Objects store related information with labels:
let student = {
name: "Ashish",
age: 20,
city: "Jaipur",
marks: 450,
course: "B.Tech"
};
console.log(student.name);
console.log(student.age);
console.log(student.city);
// Labels (keys) describe what each value represents
Real-Life Examples of Objects
Think of objects like real-world entities:
A Person: name, age, email, phone
A Car: brand, model, color, price
A Book: title, author, pages, rating
A College: name, founded year, location, ranking
2. Creating Objects
There are two main ways to create objects in JavaScript.
Method 1: Using Object Literal (Recommended)
The most common way to create an object is using curly braces {}:
let object = {
key1: value1,
key2: value2,
key3: value3
};
Method 2: Using the new Object() Constructor
You can also use the new Object() constructor, but this is less common:
let student = new Object();
student.name = "Priya";
student.age = 19;
console.log(student);
// Output: { name: 'Priya', age: 19 }
We will stick with object literals as it is simpler and more popular.
Object Properties Can Have Different Types
let person = {
name: "Ashish", // String
age: 20, // Number
isStudent: true, // Boolean
marks: [85, 90, 92], // Array
address: { // Object
city: "Jaipur",
state: "Rajasthan"
}
};
console.log(person);
Objects can contain strings, numbers, booleans, arrays, and even other objects!
3. Accessing Properties (Dot Notation and Bracket Notation)
There are two ways to access properties of an object.
Method 1: Dot Notation (Most Common)
objectName.propertyName
Example: Accessing Student Properties=
let student = {
name: "Ashish",
age: 20,
city: "Jaipur",
marks: 450
};
console.log(student.name); // Output: Ashish
console.log(student.age); // Output: 20
console.log(student.city); // Output: Jaipur
console.log(student.marks); // Output: 450
Method 2: Bracket Notation
objectName["propertyName"]
Bracket notation is useful when the property name has spaces or special characters.
Example: Using Bracket Notation
let student = {
name: "Ashish",
age: 20,
city: "Jaipur"
};
console.log(student["name"]); // Output: Ashish
console.log(student["age"]); // Output: 20
console.log(student["city"]); // Output: Jaipur
This is useful when you don't know which property to access until runtime.
Dot Notation vs Bracket Notation
| Situation | Dot Notation | Bracket Notation |
|---|---|---|
| Normal property names | obj.name |
obj["name"] |
| Property with spaces | Does not work | obj["full name"] |
| Dynamic property access | Does not work | obj[variable] |
| Readability | Better | Okay |
4. Updating Object Properties
You can change the value of a property by assigning a new value.
Syntax
objectName.propertyName = newValue;
Or with bracket notation:
objectName["propertyName"] = newValue;
Example: Updating a Single Property
let student = {
name: "Ashish",
age: 20,
marks: 450
};
console.log("Before: ", student);
// Output: Before: { name: 'Ashish', age: 20, marks: 450 }
student.age = 21; // Change age from 20 to 21
console.log("After: ", student);
// Output: After: { name: 'Ashish', age: 21, marks: 450 }
5. Adding and Deleting Properties
You can add new properties to an object at any time, and you can delete properties using the delete keyword.
Adding New Properties
let student = {
name: "Ashish",
age: 20
};
console.log("Before: ", student);
// Output: Before: { name: 'Ashish', age: 20 }
// Add new properties
student.city = "Jaipur";
student.course = "B.Tech";
console.log("After: ", student);
// Output: After: { name: 'Ashish', age: 20, city: 'Jaipur', course: 'B.Tech' }
Example : Building an Object Step by Step
let person = {};
console.log("Empty: ", person); // Output: Empty: {}
person.name = "Ashish";
console.log("After name: ", person); // Output: After name: { name: 'Ashish' }
person.age = 20;
console.log("After age: ", person); // Output: After age: { name: 'Ashish', age: 20 }
person.city = "Bangalore";
console.log("Final: ", person);
// Output: Final: { name: 'Ashish', age: 20, city: 'Bangalore' }
Deleting Properties
Use the delete keyword to remove a property from an object:
let student = {
name: "Ashish",
age: 20,
tempProperty: "remove me"
};
console.log("Before: ", student);
// Output: Before: { name: 'Ashish', age: 20, tempProperty: 'remove me' }
delete student.tempProperty;
console.log("After: ", student);
// Output: After: { name: 'Ashish', age: 20 }
6. Looping Through Object Keys
To go through all properties of an object, you can use the for...in loop.
Syntax
for (let key in objectName) {
console.log(key); // Property name
console.log(objectName[key]); // Property value
}
Example 1: Printing All Properties
let student = {
name: "Ashish",
age: 20,
city: "Jaipur",
marks: 450
};
for (let key in student) {
console.log(key + ": " + student[key]);
}
Output:
name: Ashish
age: 20
city: Jaipur
marks: 450
Example 2: Calculating Total from Object
let expenses = {
food: 5000,
transport: 2000,
entertainment: 1500,
utilities: 3000
};
let totalExpense = 0;
for (let category in expenses) {
totalExpense = totalExpense + expenses[category];
}
console.log("Total expenses: Rs. " + totalExpense); // Output: Total expenses: Rs. 11500
Using Object.keys()
You can also get all keys as an array using Object.keys():
let student = {
name: "Ashish",
age: 20,
city: "Jaipur"
};
let keys = Object.keys(student);
console.log(keys); // Output: ['name', 'age', 'city']
Visual Representation: Object Structure
Key-Value Pairs
Object: student
┌─────────────────────────┐
│ Key │ Value │
├─────────────────────────┤
│ name │ "Ashish" │
├─────────────────────────┤
│ age │ 20 │
├─────────────────────────┤
│ city │ "Jaipur"│
├─────────────────────────┤
│ marks │ 450 │
└─────────────────────────┘
Accessing:
student.name = "Ashish"
student["age"] = 20
student.city = "Jaipur"
Array vs Object Comparison
Arrays: Ordered Collection
let fruits = ["Apple", "Banana", "Mango"];
Index: 0 1 2
Value: Apple Banana Mango
Objects: Key-Value Pairs
let person = {
name: "Ashish",
age: 20,
city: "Jaipur"
};
Key: name age city
Value: Ashish 20 Jaipur
When to Use Each
| Use Case | Array | Object |
|---|---|---|
| List of items | Yes | No |
| Related data about one thing | No | Yes |
| Ordered data | Yes | No (not guaranteed) |
| Need index access | Yes | No |
| Descriptive labels | No | Yes |
Examples:
Array:
["Apple", "Banana", "Mango"](list of fruits)Object:
{ name: "Ashish", age: 20 }(person's information)
Summary
Objects are collections of key-value pairs used to store related information
Create objects using curly braces:
let obj = { key: value }Access properties using dot notation (
obj.key) or bracket notation (obj["key"])Update properties by assigning new values:
obj.key = newValueAdd properties at any time:
obj.newKey = newValueDelete properties using the
deletekeyword:delete obj.keyLoop through objects using
for...inloopObjects are perfect for representing real-world entities
Properties can have any type of value (strings, numbers, arrays, other objects, etc.)
Objects are different from arrays - use them for labeled data, not ordered lists




