learn2kode.in

JavaScript Objects

In JavaScript, an object is a collection of related data stored as key–value pairs. Objects help organize data logically and are widely used in real-world applications.

Why Use Objects?

Objects are useful when you need to store multiple related values together.

Example (without object):
let name = "John";
let age = 25;
let city = "Delhi";
Example (with object):
let user = {
  name: "John",
  age: 25,
  city: "Delhi"
};
Creating an Object
Object Literal (Recommended)
let person = {
  name: "Emma",
  age: 30,
  isStudent: false
};
Accessing Object Properties
Dot Notation
console.log(person.name); // Emma
Bracket Notation
console.log(person["age"]); // 30

Use bracket notation when the property name is dynamic or contains spaces.

Updating Object Properties
person.age = 31;
person.name = "Emma Watson";
Adding New Properties
person.country = "India";
person.email = "emma@example.com";
Deleting Object Properties
Objects with Methods

Objects can contain functions, called methods.

let car = {
  brand: "Tesla",
  model: "Model S",
  start: function () {
    console.log("Car started");
  }
};

car.start();
Nested Objects

Objects can contain other objects.

let student = {
  name: "Amit",
  marks: {
    math: 90,
    science: 85
  }
};

console.log(student.marks.math); // 90
Arrays of Objects

Used frequently in real applications like user lists or product lists.

let users = [
  { name: "John", age: 25 },
  { name: "Emma", age: 30 },
  { name: "Alex", age: 22 }
];

console.log(users[1].name); // Emma
Looping Through Objects
Using for...in Loop
let user = {
  name: "John",
  age: 25,
  city: "Delhi"
};

for (let key in user) {
  console.log(key + ": " + user[key]);
}
Useful Object Methods

Object.keys()

Object.keys(user);
// ["name", "age", "city"]
Object.values()
Object.values(user);
// ["John", 25, "Delhi"]
Object.entries()
Object.entries(user);
// [["name","John"],["age",25],["city","Delhi"]]
Object Summary Table
Feature Description Example
Create Object Group related data { name: "John" }
Access Value Get property value obj.name
Update Value Change property obj.age = 30
Add Property Add new key obj.city = "Delhi"
Delete Property Remove key delete obj.city
Loop Object Iterate keys for (key in obj)
Key Takeaways