JavaScript Arrays Basics
Arrays are ordered collections of values. They let you store multiple items in a single variable.
Creating Arrays
let empty = [];
let numbers = [1, 2, 3, 4, 5];
let fruits = ["apple", "banana", "orange"];
let mixed = [1, "hello", true, null];
Accessing Elements
Arrays use zero-based indexing:
let fruits = ["apple", "banana", "orange"];
fruits[0]; // "apple" (first element)
fruits[1]; // "banana"
fruits[2]; // "orange"
fruits[3]; // undefined (out of bounds)
Array Length
let fruits = ["apple", "banana", "orange"];
fruits.length; // 3
// Get the last element
fruits[fruits.length - 1]; // "orange"
Adding Elements
let fruits = ["apple", "banana"];
fruits.push("orange"); // Add to end
// ["apple", "banana", "orange"]
fruits.unshift("grape"); // Add to beginning
// ["grape", "apple", "banana", "orange"]
Tip: push is faster than unshift because it doesn’t reindex.
Removing Elements
let fruits = ["apple", "banana", "orange"];
let last = fruits.pop(); // Remove from end
// last = "orange"
let first = fruits.shift(); // Remove from beginning
// first = "apple"
Modifying Elements
let fruits = ["apple", "banana", "orange"];
fruits[0] = "grape"; // Change first element
fruits[3] = "mango"; // Add to specific position
Complete Example: Todo List
let todos = [];
function addTodo(text) {
todos.push({ text, done: false });
}
function completeTodo(index) {
if (index >= 0 && index < todos.length) {
todos[index].done = true;
}
}
function listTodos() {
todos.forEach((todo, i) => {
let status = todo.done ? "✓" : "○";
console.log(`${i + 1}. ${status} ${todo.text}`);
});
}
addTodo("Learn JavaScript");
addTodo("Build a project");
listTodos();
completeTodo(0);
listTodos();
Best Practices
- Use descriptive names —
fruits, notarr - Check bounds — Don’t access out-of-range indices
- Use
constfor arrays — If you won’t reassign the variable - Handle empty arrays — Check length first
- Use arrays for related data — Group logically
Common Mistakes
- Off-by-one errors — Arrays start at 0
- Forgetting length — Accessing undefined indices
- Mutating while iterating — Can skip elements
- Confusing
pushandunshift— Different performance - Using
for...inon arrays — Usefor...ofinstead