JavaScript Objects

1. What is an Object?

An object is a non-primitive data type in JavaScript that allows you to store multiple collections of data. Unlike arrays that use indexes, objects use key-value pairs. Keys are strings (or Symbols), and values can be any data type, including other objects or functions.

2. Creating an Object

The most common way to create an object is using the Object Literal syntax {}.

const person = {
    firstName: "Ragini",
    lastName: "Singh",
    age: 24,
    isStudent: false
};

document.write(person);
        
Output will appear here...

3. Accessing Properties

You can access object properties in two ways:

const car = { brand: "Toyota", model: "Corolla", "fuel type": "Hybrid" };

document.write(car.brand);         // Dot notation
document.write(car["model"]);      // Bracket notation
document.write(car["fuel type"]);  // Bracket notation required for spaces
        
Output will appear here...

4. Modifying Objects

Objects are mutable. You can add, update, or delete properties even if declared with const.

const user = { name: "Alex", role: "User" };

// Add property
user.email = "alex@example.com";

// Update property
user.role = "Admin";

// Delete property
delete user.name;

document.write(user);
        
Output will appear here...

5. Object Methods

A method is a function stored as a property. The this keyword refers to the object itself.

const student = {
    name: "Ravi",
    greet: function() {
        return "Hello, I am " + this.name;
    }
};

document.write(student.greet());
        
Output will appear here...

6. Iterating Over Objects

Use the for...in loop to iterate through keys.

const book = { title: "JS Guide", author: "John", pages: 300 };

for (let key in book) {
    document.write(key + ": " + book[key]);
}
        
Output will appear here...

7. Useful Object Methods

JavaScript provides static methods to work with objects.

const data = { a: 1, b: 2, c: 3 };

document.write(Object.keys(data));   // ["a", "b", "c"]
document.write(Object.values(data)); // [1, 2, 3]
document.write(Object.entries(data));// [["a", 1], ["b", 2], ["c", 3]]
        
Output will appear here...

8. Nested Objects

Objects can contain other objects.

const employee = {
    id: 101,
    details: {
        city: "Mumbai",
        pincode: 400001
    }
};

document.write(employee.details.city); // Mumbai
        
Output will appear here...

9. Comparison: Array vs Object

Feature Array [] Object {}
Structure Ordered List Key-Value Pairs
Access Index (0, 1, 2) Key ("name", "age")
Best For Lists of similar items Describing a single entity
Best Practice: Use objects when you need to label data (e.g., user.email). Use arrays when you have a list of items (e.g., users[0]).

Practice Questions

Test your understanding of JavaScript Objects.

Easy

Q1: Create a simple object.

  • Create an object named car.
  • Add a property brand set to "Toyota".
  • Add a property model set to "Corolla".
  • Log the object to the console.
Easy

Q2: Access object properties.

  • Given the object: const user = { name: "Alice", email: "alice@example.com" };
  • Use dot notation to access the value of the email property.
  • Log the email to the console.
Medium

Q3: Add a new property to an existing object.

  • Given the object: const book = { title: "1984", author: "George Orwell" };
  • Add a new property year with the value 2022.
  • Log the updated year property to the console.
Medium

Q4: Iterate over an object's properties.

  • Given the object: const student = { name: "John", grade: "A", age: 18 };
  • Use a for...in loop to iterate through all the keys.
  • Log each key and its corresponding value in the format "key: value".
Hard

Q5: Add a method to an object.

  • Create an object named person with properties firstName: "John" and lastName: "Doe".
  • Add a method named getFullName inside the object.
  • The method should return the combination of firstName and lastName using the this keyword.
  • Call the method and log the result to the console.

Answer

Code: