Skip to main content

Tutorial 4: Working with Arrays and Objects in JavaScript

                                               Working with Arrays and Objects in JavaScript

 

What Are Arrays?

An array is a special variable in JavaScript that allows you to store multiple values in a single variable. Arrays are ordered lists, where each value (element) is stored at an index starting from 0.

How to Create an Array:

// Example of an array
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits);  // Output: ["Apple", "Banana", "Cherry"]


Accessing Elements in an Array: You can access elements in an array using their index:

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

Modifying Elements in an Array:

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

Questions & Answers:

  1. Q: What is an array in JavaScript?
    • A: An array is a variable that can hold multiple values stored at specific indices.
  2. Q: How do you access the first element of an array?
    • A: Use the index 0, e.g., array[0].

 

Useful Array Methods

JavaScript provides many built-in methods for manipulating arrays. Here are a few essential ones:

  • Adding Elements:
    • push( ): Adds an element to the end of the array.
    • unshift( ): Adds an element to the beginning of the array.

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

fruits.unshift("Grape");
console.log(fruits);  // Output: ["Grape", "Apple", "Blueberry", "Cherry", "Mango"]
 

  • Removing Elements:
    • pop( ): Removes the last element.
    • shift ( ): Removes the first element.

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

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

  • Finding the Length of an Array:

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

  • Looping Through an Array:

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

Questions & Answers:

  1. Q: What does the push( ) method do?
    • A: It adds an element to the end of the array.
  2. Q: How can you find the number of elements in an array?
    • A: Use the .lenght property, e.g., array.length.

 

What Are Objects?

An object in JavaScript is a collection of key-value pairs. Objects allow you to store and organize related data together, making them ideal for representing real-world entities like a person or a product.

Creating an Object:

let person = {
   firstName: "John",
   lastName: "Doe",
   age: 30,
   isStudent: false
};
console.log(person);
 

Accessing Object Properties:

  • Dot Notation:

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

  • Bracket Notation:

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

Modifying Object Properties:

person.age = 31;
console.log(person.age);  // Output: 31
 

Adding New Properties:

person.country = "Canada";
console.log(person.country);  // Output: "Canada"
 

Questions & Answers:

  1. Q: What is an object in JavaScript?
    • A: An object is a collection of key-value pairs that can store multiple related data items.
  2. Q: How do you access an object's property using dot notation?
    • A: Use objectName.propertyName, e.g., person.firstName.

 

Combining Arrays and Objects

Arrays and objects often work together. For example, you might have an array of objects, where each object represents an item.

Example: Array of Objects

let students = [
   { name: "Alice", age: 20 },
   { name: "Bob", age: 22 },
   { name: "Charlie", age: 19 }
];

console.log(students[0].name);  // Output: "Alice"
console.log(students[1].age);   // Output: 22
 

Looping Through an Array of Objects:

for (let i = 0; i < students.length; i++) {
   console.log(`${students[i].name} is ${students[i].age} years old.`);
}
// Output:
// Alice is 20 years old.
// Bob is 22 years old.
// Charlie is 19 years old.
 

Questions & Answers:

  1. Q: How do you access the name property of the first object in an array?
    • A: Use arrayName[0].name, e.g., students[0].name.
  2. Q: How can you loop through an array of objects?
    • A: Use a for loop or the forEach method.

 

Practice Exercise: To-Do List Manager

Objective:
Create a simple to-do list manager using arrays and objects.

Code Example:

let toDoList = [];

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

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

// Show all tasks
function showTasks() {
   console.log("To-Do List:");
   for (let i = 0; i < toDoList.length; i++) {
       let status = toDoList[i].completed ? "✓" : "✗";
       console.log(`${i + 1}. [${status}] ${toDoList[i].task}`);
   }
}

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

Questions for Practice:

  1. Q: How do you add a new task to the to-do list?
    • A: Use the addTask(task) function.
  2. Q: How do you mark a task as completed?
    • A: Use the completTask(index) function with the task index.

 

Conclusion

Recap:

  • Arrays are ordered collections of data that allow access by index.
  • Objects store related data using key-value pairs.
  • Arrays and objects can be combined to manage more complex data structures.

Next Steps:

  • In the next tutorial, we’ll dive into DOM Manipulation and how JavaScript can dynamically update web pages.

Questions & Answers for Recap:

  1. Q: What method adds an element to the end of an array?
    • A: The push( ) method.
  2. Q: How do you add a new property to an object?
    • A: Use dot notation, e.g., object.property = value.