Welcome to Lesson 8! Arrays and objects are the backbone of data storage in JavaScript. Arrays allow you to store ordered collections of values, while objects store key-value pairs for structured data. Mastering these is essential for building complex applications.
An array is declared using square brackets []:
let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[0]); // Apple
Arrays have many useful methods:
push()– adds an element to the endpop()– removes the last elementshift()– removes the first elementunshift()– adds an element at the beginningforEach()– loops over each elementmap()– creates a new array by transforming elementsfilter()– creates a new array with elements that pass a conditionreduce()– reduces array elements to a single value
Example of looping through an array:
fruits.forEach(fruit => console.log(fruit));
Objects are declared using curly braces {} and store key-value pairs:
let user = {
name: "Alice",
age: 25,
isAdmin: true
};
console.log(user.name); // Alice
Objects can also have methods, which are functions stored as values:
let user = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
user.greet(); // Hello, Alice
Arrays and objects are often combined for real-world data, such as a list of users:
let users = [
{name: "Alice", age: 25},
{name: "Bob", age: 30}
];
users.forEach(user => console.log(user.name));
Mastering array and object manipulation allows you to handle data efficiently, such as sorting, filtering, updating, and transforming collections. These skills are vital for building apps that process dynamic content.
Practice exercises include creating a list of products, filtering them by category, updating properties dynamically, and mapping arrays to HTML elements. These exercises reinforce how arrays and objects are used in real applications.
By the end of this lesson, you should be able to:
- Create and manipulate arrays with common methods
- Create objects with properties and methods
- Loop through arrays and objects
- Combine arrays and objects for structured data
- Use arrays and objects in real-world scenarios like lists, forms, and APIs
Next, we will move on to API Requests & Fetch, which allow your web applications to communicate with external servers and services, enabling dynamic, real-time content from the internet.