Fantastic! Let's get into Arrays 📦, which are your first introduction to handling structured, collection-based data in JavaScript.
📦 Arrays: Ordered Lists
An Array is a single variable that can store a collection of different values, accessed by a numerical index. Arrays are zero-indexed, meaning the first item is at index 0.
1. Creating and Accessing Arrays
You create an array using square brackets ([]).
// Array of strings (fruits)
const fruits = ["Apple", "Banana", "Cherry", "Date"];
// Accessing elements by index
console.log(fruits[0]); // Output: Apple
console.log(fruits[3]); // Output: Date
// Finding the length (number of elements)
console.log(fruits.length); // Output: 4
// Accessing the last element using .length
console.log(fruits[fruits.length - 1]); // Output: Date
2. Modifying Arrays
Arrays are mutable, meaning you can change their contents even if declared with const.
const numbers = [10, 20, 30, 40];
// Change an element
numbers[1] = 25; // numbers is now [10, 25, 30, 40]
// Add an element to the end (.push())
numbers.push(50); // numbers is now [10, 25, 30, 40, 50]
// Remove the last element (.pop())
const removed = numbers.pop(); // removed is 50, numbers is now [10, 25, 30, 40]
3. Iterating Over Arrays (Using Loops)
This is where your for loop knowledge comes in handy. You often need to perform an action on every item in an array.
The Traditional for Loop
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(`I love the color: ${colors[i]}`);
}
The forEach Method (Modern Approach)
The forEach() method executes a provided function once for each array element. This is generally preferred for simple iteration.
colors.forEach((color) => {
// 'color' is automatically the current element
console.log(`The color is: ${color}`);
});
🏗️ Next Step: Objects
While arrays store data in an ordered list, Objects store data in descriptive, named pairs. They are the most fundamental building block for representing real-world entities in JavaScript.
Are you ready to learn about Objects?
0 Comments