JavaScript Arrays
Master JavaScript arrays for storing and manipulating collections of data.
Arrays are fundamental to JavaScript programming. They let you store multiple values in a single variable and provide powerful methods for adding, removing, and transforming data. From DOM element lists to API responses, arrays are used constantly in web development.
📚 Concepts & Theory
Creating Arrays:
const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null];
Accessing Elements:
console.log(fruits[0]); // "apple"
console.log(fruits[fruits.length - 1]); // "cherry" (last)
Common Array Methods:
// Adding elements
fruits.push("orange"); // Add to end
fruits.unshift("grape"); // Add to beginning
// Removing elements
fruits.pop(); // Remove from end
fruits.shift(); // Remove from beginning
// Finding elements
fruits.indexOf("banana"); // 1
fruits.includes("apple"); // true
Iterating Arrays:
fruits.forEach(fruit => {
console.log(fruit);
});
const upperFruits = fruits.map(f => f.toUpperCase());
🎯 Your Challenge
Create an array called `colors` with "red", "green", "blue". Add "yellow" to the end using push(). Then find the index of "green" and store it in a variable called `greenIndex`.
📝 Starter Code
// Create the colors array
const colors =
// Add "yellow" to the end
// Find the index of "green"
const greenIndex =
- Arrays use square brackets []
- push() adds to the end of an array
- indexOf() returns the position of an element
- Array indexes start at 0, not 1
Solution
const colors = ["red", "green", "blue"];
colors.push("yellow");
const greenIndex = colors.indexOf("green");
Explanation
We create the array with square brackets and string values. The push() method adds "yellow" to the end, making the array ["red", "green", "blue", "yellow"]. indexOf() returns 1 because "green" is at index 1 (arrays are zero-indexed).
⚠️ Common Mistakes to Avoid
- Using add() instead of push()
- Forgetting that arrays are zero-indexed
- Using find() instead of indexOf() for position
- Not including const when declaring the array