JavaScript Arrays Basics
Introduction
Arrays are one of the most fundamental data structures in JavaScript. They allow you to store multiple values in a single variable, which makes organizing and managing related data much easier. Whether you're building a simple to-do list or a complex web application, understanding arrays is essential for effective JavaScript programming.
In this lesson, we'll explore the basics of JavaScript arrays, including how to create them, access their elements, modify them, and perform common operations.
What is an Array?
An array in JavaScript is an ordered collection of values. These values can be of any type, including numbers, strings, objects, or even other arrays. Think of an array as a list of items stored in a specific order.
Creating Arrays
There are several ways to create arrays in JavaScript:
Array Literal Notation
The most common way to create an array is using array literal notation with square brackets []
:
// Empty array
const emptyArray = [];
// Array with numbers
const numbers = [1, 2, 3, 4, 5];
// Array with strings
const fruits = ["apple", "banana", "orange"];
// Mixed array with different data types
const mixed = [42, "hello", true, null, { name: "John" }];
// Nested arrays
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
Array Constructor
You can also create arrays using the Array()
constructor:
// Empty array
const emptyArray = new Array();
// Array with a predefined length
const arrayWithLength = new Array(5); // Creates an array with 5 empty slots
// Array with specific elements
const fruits = new Array("apple", "banana", "orange");
Accessing Array Elements
Array elements are accessed using their index, which starts at 0 for the first element:
const colors = ["red", "green", "blue", "yellow"];
console.log(colors[0]); // Output: "red"
console.log(colors[1]); // Output: "green"
console.log(colors[2]); // Output: "blue"
console.log(colors[3]); // Output: "yellow"
// Accessing an element that doesn't exist returns undefined
console.log(colors[4]); // Output: undefined
Negative Indexes
Unlike some programming languages, JavaScript doesn't natively support negative indexes:
const colors = ["red", "green", "blue"];
console.log(colors[-1]); // Output: undefined (not the last element)
However, you can use the array's length to access elements from the end:
const colors = ["red", "green", "blue"];
console.log(colors[colors.length - 1]); // Output: "blue" (last element)
Array Properties and Basic Methods
Length Property
The length
property returns the number of elements in an array:
const fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // Output: 3
// Interesting behavior: setting length can truncate the array
fruits.length = 2;
console.log(fruits); // Output: ["apple", "banana"]
Adding Elements to an Array
There are several ways to add elements to an array:
const numbers = [1, 2, 3];
// Add to the end with push (returns new length)
const newLength = numbers.push(4, 5);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(newLength); // Output: 5
// Add to the beginning with unshift (returns new length)
const length2 = numbers.unshift(0);
console.log(numbers); // Output: [0, 1, 2, 3, 4, 5]
console.log(length2); // Output: 6
Removing Elements from an Array
Similarly, there are methods for removing elements:
const letters = ["a", "b", "c", "d", "e"];
// Remove from the end with pop (returns removed element)
const lastElement = letters.pop();
console.log(letters); // Output: ["a", "b", "c", "d"]
console.log(lastElement); // Output: "e"
// Remove from the beginning with shift (returns removed element)
const firstElement = letters.shift();
console.log(letters); // Output: ["b", "c", "d"]
console.log(firstElement); // Output: "a"
Modifying Arrays
Arrays in JavaScript are mutable, meaning you can change their content after creation:
const pets = ["cat", "dog", "fish"];
// Change an element by index
pets[1] = "bird";
console.log(pets); // Output: ["cat", "bird", "fish"]
// Add a new element by index (can create "holes" if index exceeds length)
pets[3] = "rabbit";
console.log(pets); // Output: ["cat", "bird", "fish", "rabbit"]
pets[6] = "hamster";
console.log(pets); // Output: ["cat", "bird", "fish", "rabbit", empty × 2, "hamster"]
console.log(pets.length); // Output: 7
Common Array Operations
Finding Elements
To check if an array contains a specific value:
const fruits = ["apple", "banana", "orange", "mango"];
// Using indexOf (returns index or -1 if not found)
const bananaIndex = fruits.indexOf("banana");
console.log(bananaIndex); // Output: 1
const grapeIndex = fruits.indexOf("grape");
console.log(grapeIndex); // Output: -1
// Using includes (returns true or false)
console.log(fruits.includes("mango")); // Output: true
console.log(fruits.includes("pear")); // Output: false
Joining Arrays
You can combine arrays using the concat()
method:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = arr1.concat(arr2);
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]
console.log(arr1); // Output: [1, 2, 3] (original arrays are not modified)
Slicing Arrays
Extract a portion of an array without modifying the original:
const numbers = [10, 20, 30, 40, 50];
// slice(start, end) - end is exclusive
const slice1 = numbers.slice(1, 4);
console.log(slice1); // Output: [20, 30, 40]
// Omitting end will go to the end of the array
const slice2 = numbers.slice(2);
console.log(slice2); // Output: [30, 40, 50]
// Negative indexes count from the end
const slice3 = numbers.slice(-2);
console.log(slice3); // Output: [40, 50]
Splicing Arrays
Modify an array by removing, replacing, or adding elements:
const colors = ["red", "green", "blue", "yellow", "purple"];
// splice(start, deleteCount, item1, item2, ...)
// Returns removed items as a new array
// Remove 2 elements starting at index 1
const removed1 = colors.splice(1, 2);
console.log(colors); // Output: ["red", "yellow", "purple"]
console.log(removed1); // Output: ["green", "blue"]
// Insert without removing
colors.splice(1, 0, "orange", "pink");
console.log(colors); // Output: ["red", "orange", "pink", "yellow", "purple"]
// Replace elements
colors.splice(3, 2, "black", "white");
console.log(colors); // Output: ["red", "orange", "pink", "black", "white"]
Converting Arrays to Strings
JavaScript provides methods to convert arrays to strings:
const fruits = ["apple", "banana", "orange"];
// Join elements with a separator
const fruitsStr = fruits.join(", ");
console.log(fruitsStr); // Output: "apple, banana, orange"
// Without a separator (default is comma)
const simpleStr = fruits.join();
console.log(simpleStr); // Output: "apple,banana,orange"
// toString() also converts to comma-separated string
const toStr = fruits.toString();
console.log(toStr); // Output: "apple,banana,orange"
Practical Example: To-Do List
Here's a simple example of how arrays might be used in a to-do list application:
// Initialize an empty to-do list
let todoList = [];
// Add items to the list
function addTask(task) {
todoList.push(task);
console.log(`Task added: ${task}`);
return todoList.length;
}
// Remove a task by index
function removeTask(index) {
if (index >= 0 && index < todoList.length) {
const removedTask = todoList.splice(index, 1)[0];
console.log(`Removed task: ${removedTask}`);
return true;
} else {
console.log("Invalid task index");
return false;
}
}
// Display the current list
function displayTasks() {
if (todoList.length === 0) {
console.log("Your to-do list is empty!");
} else {
console.log("Your To-Do List:");
todoList.forEach((task, index) => {
console.log(`${index + 1}. ${task}`);
});
}
}
// Example usage
addTask("Buy groceries");
addTask("Walk the dog");
addTask("Complete JavaScript homework");
displayTasks();
// Output:
// Your To-Do List:
// 1. Buy groceries
// 2. Walk the dog
// 3. Complete JavaScript homework
removeTask(1);
// Output: Removed task: Walk the dog
displayTasks();
// Output:
// Your To-Do List:
// 1. Buy groceries
// 2. Complete JavaScript homework
Summary
In this lesson, we've covered the basics of JavaScript arrays:
- Creating arrays using literal notation and constructors
- Accessing array elements by index
- Modifying arrays with methods like
push
,pop
,shift
, andunshift
- Common operations like finding elements, joining arrays, and extracting portions
- Converting arrays to strings with
join()
andtoString()
Arrays are incredibly versatile and form the backbone of many JavaScript applications. As you continue learning JavaScript, you'll discover many more powerful ways to work with arrays, including advanced methods for iteration, transformation, and filtering.
Exercises
To solidify your understanding, try these exercises:
- Create an array of your favorite books and log the first and last elements.
- Write a function that takes an array and returns a new array with elements in reverse order (without using the built-in
reverse()
method). - Create a shopping cart array and write functions to add items, remove items, and calculate the total cost.
- Write a function that takes two arrays and returns a new array containing only the common elements.
- Create a function that flattens a nested array (e.g.,
[[1,2], [3,4]]
becomes[1,2,3,4]
) without using built-in methods likeflat()
.
Additional Resources
- MDN Web Docs: Arrays
- JavaScript.info: Arrays
- W3Schools: JavaScript Arrays
- Eloquent JavaScript: Data Structures: Arrays
In the next lesson, we'll explore more advanced array methods like map()
, filter()
, and reduce()
which are essential for modern JavaScript development.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)