Objects

In JavaScript, objects are used to store multiple pieces of related data and functionality. Think of an object as a collection of key-value pairs, where each key is a property (or method), and each value holds the data or function for that property.

What is an Object?

An object is like a real-world object. For example:

  • A car has properties like color and model and methods like drive and stop.
  • A person has properties like name and age and methods like speak.

Example: Simple Object

Javascript
Copy
let person = {
  name: "Alice",     // Property
  age: 25,           // Property
  speak: function () { // Method
    console.log("Hello!");
  }
};

console.log(person.name); // Outputs: Alice
person.speak();           // Outputs: Hello!

How to Create an Object

a) Object Literal

This is the easiest and most common way to create an object.

Javascript
Copy
let car = {
  brand: "Toyota",
  color: "Red",
  start: function () {
    console.log("Car is starting...");
  }
};

b) Using the new Object() Syntax

You can also create an object using the Object constructor.

Javascript
Copy
let person = new Object();
person.name = "Bob";
person.age = 30;

console.log(person.name); // Outputs: Bob

Accessing Object Properties

You can access properties in two ways:
  1. Dot Notation: objectName.propertyName
  2. Bracket Notation: objectName["propertyName"]

Example:

Javascript
Copy
let book = {
  title: "The Alchemist",
  author: "Paulo Coelho"
};

console.log(book.title);          // Dot notation: Outputs: The Alchemist
console.log(book["author"]);      // Bracket notation: Outputs: Paulo Coelho

Adding and Modifying Properties

You can add or modify properties directly using dot or bracket notation.

Example:

Javascript
Copy
let laptop = {
  brand: "Dell"
};

// Adding a new property
laptop.model = "XPS 13";

// Modifying an existing property
laptop.brand = "HP";

console.log(laptop); // Outputs: { brand: "HP", model: "XPS 13" }

Removing Properties

Use the delete keyword to remove a property.

Example:

Javascript
Copy
let user = {
  name: "Emma",
  age: 28
};

delete user.age;

console.log(user); // Outputs: { name: "Emma" }

Methods in Objects

A method is a function inside an object.

Example:

Javascript
Copy
let calculator = {
  add: function (a, b) {
    return a + b;
  },
  subtract: function (a, b) {
    return a - b;
  }
};

console.log(calculator.add(5, 3));       // Outputs: 8
console.log(calculator.subtract(10, 4)); // Outputs: 6

Looping Through Object Properties

Use the for...in loop to iterate through all properties of an object.

Example:

Javascript
Copy
let person = {
  name: "Sophia",
  age: 22,
  country: "USA"
};

for (let key in person) {
  console.log(key + ": " + person[key]);
}
// Outputs:
// name: Sophia
// age: 22
// country: USA

Object Methods

a) Object.keys()

Returns an array of the object's keys.

Javascript
Copy
let person = {
  name: "Sophia",
  age: 22,
  country: "USA"
};

for (let key in person) {
  console.log(key + ": " + person[key]);
}
// Outputs:
// name: Sophia
// age: 22
// country: USA

b) Object.values()

Returns an array of the object's values.

Javascript
Copy
console.log(Object.values(car)); // Outputs: ["Ford", "Mustang"]

c) Object.entries()

Returns an array of key-value pairs.

Javascript
Copy
console.log(Object.entries(car)); // Outputs: [["brand", "Ford"], ["model", "Mustang"]]

Nested Objects

Objects can contain other objects.

Example:
Javascript
Copy
let student = {
  name: "Alex",
  grades: {
    math: 90,
    science: 85
  }
};

console.log(student.grades.math); // Outputs: 90

this Keyword in Objects

The this keyword refers to the current object.

Javascript
Copy
let person = {
  name: "John",
  greet: function () {
    console.log("Hello, my name is " + this.name);
  }
};

person.greet(); // Outputs: Hello, my name is John

Example Program: Student Object

Here's a simple program using an object to manage a student's information.

Javascript
Copy
let student = {
  name: "Maria",
  grades: [80, 85, 90],
  addGrade: function (grade) {
    this.grades.push(grade);
  },
  calculateAverage: function () {
    let total = 0;
    for (let grade of this.grades) {
      total += grade;
    }
    return total / this.grades.length;
  }
};

student.addGrade(95);
console.log(student.calculateAverage()); // Outputs: 87.5

Advantages of Objects

  1. Data Grouping: Group related data and functionality.
  2. Code Reusability: Use methods for repetitive tasks.
  3. Clear Structure: Makes code organized and readable.