Module 9: Objects and Arrays

Objective: Learn how to work with objects and arrays in JavaScript, which are essential for organizing and managing data in your programs.

1. What Are Objects?

An object is a collection of related data and functions (called properties and methods). Objects are useful for representing things with multiple attributes, like a person or a car.

Real-Life Analogy:

Think of an object as a backpack that contains multiple labeled items:

  • A water bottle (property: water).
  • A notebook (property: notebook).
  • A flashlight (method: turnOn()).

2. Creating an Object

Objects are created using curly braces {}.

Syntax:

let objectName = {
    key1: value1,
    key2: value2,
    // more properties
};

Example:

let person = {
    name: "Alice",
    age: 25,
    isStudent: true
};

3. Accessing Object Properties

You can access properties using dot notation or bracket notation.

Example:

let person = {
    name: "Alice",
    age: 25
};

console.log(person.name); // Outputs: Alice (dot notation)
console.log(person["age"]); // Outputs: 25 (bracket notation)

4. Adding and Updating Properties

You can add new properties or update existing ones.

Example:

let car = {
    brand: "Toyota",
    color: "red"
};

// Add a new property
car.model = "Corolla";

// Update a property
car.color = "blue";

console.log(car);

5. Methods in Objects

A method is a function stored inside an object.

Example:

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

6. What Are Arrays?

An array is a list of values stored in a single variable. Arrays are great for storing collections of similar items, like a list of names or numbers.

Example:

let fruits = ["apple", "banana", "cherry"];

7. Accessing Array Elements

Array elements are accessed using their index (starting at 0).

Example:

let fruits = ["apple", "banana", "cherry"];

console.log(fruits[0]); // Outputs: apple
console.log(fruits[2]); // Outputs: cherry

8. Adding, Removing, and Modifying Elements

Arrays have built-in methods for managing elements.

MethodDescriptionExample
push()Adds an element to the end of the arrayfruits.push("grape");
pop()Removes the last elementfruits.pop();
unshift()Adds an element to the beginningfruits.unshift("kiwi");
shift()Removes the first elementfruits.shift();
splice()Adds/removes elements at a specific positionfruits.splice(1, 1, "pear");

Example:

let fruits = ["apple", "banana", "cherry"];

fruits.push("grape"); // Add to the end
console.log(fruits); // ["apple", "banana", "cherry", "grape"]

fruits.pop(); // Remove the last element
console.log(fruits); // ["apple", "banana", "cherry"]

fruits.unshift("kiwi"); // Add to the beginning
console.log(fruits); // ["kiwi", "apple", "banana", "cherry"]

fruits.splice(1, 1, "pear"); // Replace 'apple' with 'pear'
console.log(fruits); // ["kiwi", "pear", "banana", "cherry"]

9. Iterating Over Arrays

Use loops to process each element in an array.

Example: Using a for Loop

let fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

10. Objects vs. Arrays

FeatureObjectsArrays
Use CaseGroup related data with keysStore ordered lists of similar items
AccessBy key (object.key)By index (array[index])
OrderUnorderedOrdered

11. Practice Exercises

Task 1: Create a Person Object

  1. Create an object called person with the following properties:
    • Name
    • Age
    • A method greet that logs a greeting message.

Example Solution:

let person = {
    name: "Alice",
    age: 25,
    greet: function() {
        console.log("Hello, my name is " + this.name + "!");
    }
};

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

Task 2: Fruit Basket

  1. Create an array called basket with a list of fruits.
  2. Add a fruit to the end.
  3. Remove the first fruit.
  4. Print all the fruits.

Example Solution:

let basket = ["apple", "orange", "banana"];

basket.push("cherry"); // Add to the end
basket.shift(); // Remove the first fruit

for (let fruit of basket) {
    console.log(fruit);
}

12. Challenge: Shopping Cart

  1. Create an object called cart with:
    • A property items (an array of item names).
    • A method addItem to add an item to the cart.
    • A method removeItem to remove an item by name.
    • A method listItems to print all items.

Example Solution:

let cart = {
    items: [],
    addItem: function(item) {
        this.items.push(item);
    },
    removeItem: function(item) {
        let index = this.items.indexOf(item);
        if (index !== -1) {
            this.items.splice(index, 1);
        }
    },
    listItems: function() {
        console.log("Cart items:", this.items);
    }
};

cart.addItem("apple");
cart.addItem("banana");
cart.listItems(); // Outputs: Cart items: [ 'apple', 'banana' ]
cart.removeItem("apple");
cart.listItems(); // Outputs: Cart items: [ 'banana' ]

13. Common Errors

  1. Accessing Nonexistent Properties:

    let person = { name: "Alice" };
    console.log(person.age); // undefined
  2. Using Wrong Array Index:

    let fruits = ["apple", "banana"];
    console.log(fruits[5]); // undefined