JavaScript Objects

Learn how to create and use objects in JavaScript to store collections of data.

Introduction to Objects

Objects are collections of key-value pairs. They allow you to group related data and functions.

Creating Objects:

Objects are created using curly braces {} and key-value pairs:


let person = {
  name: "Alice",
  age: 25,
  isStudent: true
};
            
let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    greet: function() {
        console.log("Hello, " + this.firstName);
    }
};

console.log(person.firstName);  // Output: John
person.greet();  // Output: Hello, John

Accessing Properties:

You can access object properties using dot or bracket notation:


console.log(person.name);        // Alice
console.log(person["age"]);      // 25
            

Modifying Properties

You can update or add new properties:


person.age = 26;
person.city = "Delhi";
console.log(person);
            

Looping Through Objects

Use for...in to loop through object keys:


for (let key in person) {
  console.log(key + ": " + person[key]);
}
            

Nested Objects

Objects can contain other objects or arrays:


let student = {
  name: "John",
  address: {
    city: "Mumbai",
    zip: 400001
  }
};

console.log(student.address.city); // Mumbai
            

Useful Methods

  • Object.keys(obj) – Returns array of keys
  • Object.values(obj) – Returns array of values
  • Object.entries(obj) – Returns array of key-value pairs

console.log(Object.keys(person));   // ["name", "age", "isStudent", "city"]
console.log(Object.values(person)); // ["Alice", 26, true, "Delhi"]
            

Practice Task

Create an object to store information about a book and log each key and value:


let book = {
  title: "JavaScript Guide",
  author: "CodingRider",
  pages: 300
};

for (let key in book) {
  console.log(key + ": " + book[key]);
}