Skip to main content

Tutorial 4: Working with Arrays and Objects in JavaScript

 

Understanding Arrays

An array is a special type of variable in JavaScript that allows you to store multiple values in a single container. Arrays are ordered, meaning each item is assigned an index starting from 0. 

Syntax to Declare an Array:

    let fruits = ["Apple", "Banana", "Cherry"];


Accessing Array Elements:

    console.log(fruits[0]);  // Output: "Apple"
    console.log(fruits[2]);  // Output: "Cherry"
 

Modifying an Array:

    fruits[1] = "Blueberry";  
    console.log(fruits);  // Output: ["Apple", "Blueberry", "Cherry"]

Adding New Items to an Array:

    fruits.push("Mango");  // Adds "Mango" at the end
    console.log(fruits);  // Output: ["Apple", "Blueberry", "Cherry", "Mango"]

Common Array Methods

JavaScript provides powerful methods for working with arrays. Here are some commonly used ones:

Adding and Removing Elements:

  • push ( ) : Adds an element to the end.
  • pop ( ) : Removes the last element.
  • shift ( ) : Removes the first element.
  • unshift ( ) : Adds an element to the beginning.

Example:

    let animals = ["Dog", "Cat", "Rabbit"];
    animals.push("Horse");  // Add at the end
    animals.shift();        // Remove the first element
    console.log(animals);   // Output: ["Cat", "Rabbit", "Horse"]
 

Finding Array Length:

    console.log(animals.length);  // Output: 3
 

Iterating Through an Array:

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


Questions & Answers:

  1. Q: What does the pop ( ) method do?
    • A: It removes the last element from the array.
  2. Q: How can you find the number of elements in an array?
    • A: Use the length property, e.g., array.length.
    •  

What Are Objects?

An object in JavaScript is a collection of properties, where each property has a name (key) and a value. Objects are great for storing related data.

Syntax to Declare an Object:

    let person = {
       firstName: "Alice",
       lastName: "Smith",
       age: 25
    };


Accessing Object Properties:

  • Dot Notation:

      console.log(person.firstName);  // Output: "Alice"

  • Bracket Notation:

      console.log(person["lastName"]);  // Output: "Smith"

 

Adding or Updating Properties:

    person.age = 26;  // Update an existing property
    person.city = "Toronto";  // Add a new property
    console.log(person);

 

Nested Arrays and Objects

Arrays and objects can be combined to create complex data structures.

Array of Objects:

    let students = [
       { name: "John", age: 20 },
       { name: "Emma", age: 22 },
       { name: "Ryan", age: 19 }
    ];

    console.log(students[0].name);  // Output: "John"
 

Object with Arrays:

    let classroom = {
       teacher: "Mr. Lee",
       students: ["John", "Emma", "Ryan"]
    };

    console.log(classroom.students[1]);  // Output: "Emma"

Questions & Answers:

  1. Q: How do you access the name of the second student in an array of objects?
    • A: Use arrayName[1].name.
  2. Q: Can arrays hold objects as their elements?
    • A: Yes, arrays can hold objects, and objects can include arrays as their properties.

Practice Challenge: To-Do List

Objective:

Create a simple to-do list program using an array to store tasks.

Code Example:

    let toDoList = [];

    // Add a task
    function addTask(task) {
     toDoList.push({ task: task, completed: false });
     console.log(`Added: "${task}"`);
    }

    // Mark a task as complete
    function completeTask(index) {
     if (toDoList[index]) {
         toDoList[index].completed = true;
         console.log(`Task "${toDoList[index].task}" marked as complete.`);
     } else {
       console.log("Invalid task index.");
     }
    }

    // View all tasks
    function viewTasks() {
     console.log("To-Do List:");
     toDoList.forEach((task, index) => {
       let status = task.completed ? "✓" : "✗";
         console.log(`${index + 1}. [${status}] ${task.task}`);
     });
  }

    // Example Usage
   addTask("Learn JavaScript");
   addTask("Build a to-do app");
   viewTasks();
   completeTask(0);
   viewTasks();

 

Additional Practice

  1. Array Practice:
    Write a program to find the largest number in an array.
  2. Object Practice:
    Create an object to represent a car. Add properties like make, model, and year. Add a method startCar ( ) that prints "This car is starting. " . 
     

Conclusion

Recap:

  • Arrays store ordered lists of values, while objects store key-value pairs.
  • You can combine arrays and objects to manage more complex data.
  • JavaScript provides many useful methods for working with arrays and objects.

Next Steps:

  • Explore DOM Manipulation in the next tutorial to learn how JavaScript interacts with web pages.