What is an Array?
An array is a special variable that holds multiple values in an ordered list. You can store numbers, strings, objects, or even other arrays.
💡 Real-world analogy
Think of an array like a numbered list. Each item has a position (index) starting from 0, just like items on a grocery list.
Creating Arrays
// Array literal (preferred)
let fruits = ["apple", "banana", "orange"];
// Using the Array constructor
let numbers = new Array(1, 2, 3, 4, 5);
// Empty array
let empty = [];
Accessing Array Elements
Use square brackets with the index (starting from 0).
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "orange"
console.log(fruits.length); // 3
Common Array Methods
push()— add an item to the endpop()— remove the last itemunshift()— add an item to the beginningshift()— remove the first itemincludes()— check if an item existsindexOf()— find the index of an itemslice()— create a copy of part of the arraysplice()— add or remove items at a specific index
Looping Through Arrays
let fruits = ["apple", "banana", "orange"];
// Traditional for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// for...of loop (cleaner)
for (let fruit of fruits) {
console.log(fruit);
}
Common Mistakes
- Off-by-one errors with array indices (arrays start at 0)
- Modifying arrays while iterating over them
- Using
==to compare arrays (use===or compare elements)
Quick Quiz
1. What is the index of the last element in an array of length 5?
2. Which method adds an item to the end of an array?
3. What does fruits[0] give you?
Summary
- Arrays hold ordered lists of values
- Index starts at 0
push()andpop()work with the end of the arrayunshift()andshift()work with the beginningincludes()andindexOf()help find itemsslice()copies part of an array;splice()modifies it
