What Is an Array?
An array is a fundamental data structure used to store multiple values in a single collection. Each value is stored at a specific position called an index, which makes it possible to access individual elements efficiently.
Arrays are one of the most commonly used data structures because they provide a simple way to organize and process collections of related data. For example, an application may use an array to store product prices, student scores, user names, or the results of a search.
const scores = [85, 92, 78, 96, 88];
console.log(scores[0]); // 85
console.log(scores[3]); // 96
In JavaScript, array indexes start at 0. Therefore, the first element is at
index 0, the second element is at index 1, and so on.
How Array Indexing Works
Consider the following array:
const languages = ['JavaScript', 'Python', 'Java', 'C#'];
| Index | Value |
|---|---|
| 0 | JavaScript |
| 1 | Python |
| 2 | Java |
| 3 | C# |
The index provides a direct way to identify an element. To access the third element, use
languages[2].
Array Elements and Length
The length property tells you how many elements are currently stored in a JavaScript
array.
const numbers = [10, 20, 30, 40];
console.log(numbers.length); // 4
console.log(numbers[0]); // 10
console.log(numbers[3]); // 40
The last valid index is always length - 1. For an array with four elements, the last
index is 3.
Creating Arrays in JavaScript
JavaScript provides several ways to create arrays. The most common approach is using array literal syntax.
const fruits = ['Apple', 'Banana', 'Orange'];
const emptyArray = [];
const values = [10, 20, 30];
const mixedValues = ['IgKnight', 100, true];
JavaScript arrays can contain values of different types. However, when designing applications, keeping collections logically consistent usually makes the code easier to understand and maintain.
Basic Array Operations
Arrays support several operations for adding, removing, accessing, updating, searching, and processing elements.
| Operation | Example | Purpose |
|---|---|---|
| Access | arr[2] |
Read an element |
| Update | arr[2] = 50 |
Change an element |
| Insert at end | arr.push(50) |
Add an element |
| Remove from end | arr.pop() |
Remove the last element |
| Search | arr.indexOf(50) |
Find an element |
These operations are explored in more detail in the following array topics, including insertion, deletion, traversal, searching, and updating.
Accessing and Updating Elements
One of the main strengths of an array is direct access to elements by index. If you know the position of an element, you can access it without scanning the entire collection.
const users = ['Alice', 'Bob', 'Charlie'];
console.log(users[1]); // Bob
users[1] = 'David';
console.log(users); // ['Alice', 'David', 'Charlie']
Accessing an element by index is generally considered an O(1) operation in a conventional array representation because the position can be calculated directly.
Traversing an Array
Traversal means visiting the elements of an array, usually from the first element to the last. A loop is commonly used for traversal.
const numbers = [10, 20, 30, 40];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
Traversing all n elements requires O(n) time because every element
must be visited.
Array Memory and Storage
In traditional array implementations, elements are stored in a contiguous region of memory. Because the elements have predictable positions, the address of an element can be calculated from its index.
JavaScript arrays are more flexible than fixed-size arrays in lower-level languages. JavaScript arrays are objects with specialized array behavior, so their internal representation can vary depending on the JavaScript engine and how the array is used.
The important data-structure concept is that arrays provide indexed access and are designed to efficiently work with ordered collections.
Time Complexity of Common Array Operations
| Operation | Typical Complexity |
|---|---|
| Access by index | O(1) |
| Update by index | O(1) |
| Traversal | O(n) |
| Linear search | O(n) |
| Insertion at end | O(1) amortized for dynamic arrays |
| Insertion or deletion near the beginning | O(n) |
The exact performance of some JavaScript array operations depends on the operation and the JavaScript engine. For data-structure analysis, the complexity above provides the standard model used when reasoning about arrays and dynamic arrays.
Advantages of Arrays
- Simple and easy to understand.
- Provides efficient indexed access.
- Works well for ordered collections of elements.
- Supports efficient sequential traversal.
- Widely supported across programming languages.
- Forms the foundation for many other algorithms and data structures.
Limitations of Arrays
- Searching for an unknown value can require O(n) time.
- Inserting elements in the middle can require shifting other elements.
- Deleting elements from the middle can also require shifting elements.
- Fixed-size arrays cannot automatically grow without allocating new storage.
- Arrays may not be the best choice when frequent insertions and deletions are required.
Arrays in Real-World Applications
Arrays appear throughout software development because many applications need to process collections of related values.
- Storing lists of users, products, or orders.
- Managing scores and measurements.
- Representing rows and columns in matrix-based problems.
- Processing search results.
- Implementing stacks, queues, and heaps.
- Supporting sorting and searching algorithms.
- Representing collections used by application interfaces.
When Should You Use an Array?
Arrays are a strong choice when your application needs an ordered collection and frequent access by position. They are especially useful when the number of elements is known or when additions and removals are relatively infrequent compared with reads.
If your application frequently inserts or removes elements from the middle of a collection, another data structure such as a linked list may be more appropriate depending on the workload.
Arrays and Other Data Structures
| Data Structure | Useful When |
|---|---|
| Array | Fast indexed access is important |
| Linked List | Frequent structural insertions and deletions are important |
| Hash Table | Fast key-based lookup is required |
| Tree | Hierarchical or ordered relationships are required |
Common Beginner Mistakes
- Forgetting that JavaScript array indexes start at zero.
- Trying to access an element using an invalid index.
- Confusing an array's length with its last index.
- Assuming every array operation has O(1) complexity.
- Using arrays when frequent middle insertions and deletions dominate the workload.
Key Takeaways
- An array stores multiple elements in an ordered collection.
- Elements are accessed using indexes.
- JavaScript arrays use zero-based indexing.
- Accessing an element by index is typically O(1).
- Traversing or linearly searching an array requires O(n) time.
- Insertions and deletions can become expensive when elements must be shifted.
- Arrays are a foundation for many other data structures and algorithms.