Introduction to Arrays
Getting to Know Arrays
An array
is one of the fundamental data types in JavaScript, as well as in most other programming languages. At its core, an array is an ordered collection of values, where each value is referred to as an element
. These elements are stored in a specific sequence, and each one has a numeric position known as its index
.
In JavaScript, arrays are quite flexible. They are untyped
, meaning you can store any type of data in an array—numbers, strings, objects, or even other arrays—and different elements in the same array can be of different types. JavaScript arrays are also zero-based
, which means that the first element has an index of 0
. The largest possible index is 4,294,967,294
, giving you a potential maximum array size of 4,294,967,295
elements.
One of the powerful features of JavaScript arrays is their dynamic
nature. You don’t need to specify a fixed size when you create an array; it can grow or shrink as needed. This flexibility makes arrays incredibly useful in a wide range of situations.
Behind the scenes, JavaScript engines typically optimize arrays so that accessing elements by their numeric index is much faster than accessing regular object properties. Additionally, with the introduction of ES6
, JavaScript gained a new set of array classes known as “typed arrays
,” which allow for more efficient handling of arrays containing specific types of data.
Creating Arrays
When it comes to creating arrays in JavaScript, you have several options, but the easiest and most straightforward method is using an array literal
. An array literal is just a list of elements separated by commas and enclosed in square brackets.
For example:
In this example, fruits
is an array containing three elements: "apple", "banana", and "cherry".
One neat thing about array literals is that you can include an optional trailing comma at the end. This doesn’t add an extra element but can make editing the array easier. For instance, [,,]
creates an array with two undefined
elements, giving it a length of 2
, not 3
.
Starting with ES6
, you can also use the “spread operator
” (...
) to include elements from one array within another. This is particularly useful when you want to merge arrays or include all elements from an existing array into a new one.
For example:
Here, moreFruits
becomes ['mango', 'apple', 'banana', 'cherry', 'pineapple']
, seamlessly including all the elements from the fruits
array along with "mango" and "pineapple".
We can explore more ways of creating arrays in the future as you upgrade belts!
Reading and Writing Elements
In JavaScript, you access an element of an array using the square brackets []
operator. To do this, you place the reference to the array on the left side of the brackets, and inside the brackets, you provide an expression that evaluates to a non-negative integer. This allows you to both read and write values to specific positions within the array.
For example:
What makes arrays special in JavaScript is that when you use numeric property names (like 0
, 1
, 2
, etc.) that are non-negative integers less than 2^32 - 1
, the array automatically keeps track of its length
property for you.
For example:
Remember, arrays in JavaScript are a specialized type of object. The square brackets used to access array elements work the same way as the square brackets used to access object properties. When you use an index like 1
, JavaScript converts it to a string "1"
and uses that string as a property name. This isn't unique to arrays; you can do the same with regular objects:
It’s helpful to understand the difference between an array index and an object property name. All array indexes are property names, but only property names that are positive integers are considered indexes. Arrays are still objects, so you can add properties with any name:
If you use properties that qualify as array indexes (non-negative integers less than 2^32 - 1
), the array will automatically update its length
property. However, if you use numbers that are negative or not integers as indexes, JavaScript converts them to strings and treats them as regular object properties, not array indexes.
Since array indexes are simply a type of object property name, JavaScript arrays don’t have an “out of bounds” error. If you try to access a non-existent property, JavaScript doesn’t throw an error; it simply returns undefined
. This behavior is consistent between arrays and regular objects:
Understanding these concepts will help you use arrays more effectively and avoid common pitfalls when working with JavaScript.
Adding & Deleting Array Elements
In JavaScript, there are several methods to manipulate the elements of an array easily.
push()
If you want to add one or more values to the end of an array, you can use the push()
method. It appends the new elements and automatically updates the array's length
.
For example:
unshift()
Similarly, if you want to add elements to the beginning of an array, use the unshift()
method. This method adds the new values to the start and shifts the existing elements to higher indexes to make space for the new ones.
pop()
The pop()
method works in the opposite way to push()
. It removes the last element of an array and returns it, reducing the array's length
by 1.
shift()
Likewise, the shift()
method removes the first element of an array and returns it. This method also reduces the array's length
by 1 and shifts all remaining elements down to a lower index.
delete
You can also remove elements from an array using the delete
operator, just as you would delete a property from an object. However, there are a few important distinctions to keep in mind. Using delete
does not affect the array’s length
property and does not shift elements with higher indexes to fill the gap left by the deleted element.
For example:
Using delete
on an array creates a "sparse array" with gaps. It's different from setting an element to undefined
, which still leaves the element in the array.
If you want to remove elements from the end of an array without creating gaps, you can directly set the length
property to a new, shorter length.
These methods give you a lot of flexibility when managing arrays in JavaScript. However, be mindful of how each method affects the array to avoid unintended consequences, like creating sparse arrays.
Iterating Arrays
As of ES6
, one of the simplest and most readable ways to loop through each element of an array (or any iterable object) is by using the for...of
loop. This loop automatically goes through each item in the array, from the first to the last, in ascending order.
For example:
If you need to access both the index and the value of each element while using the for...of
loop, you can combine it with the entries()
method and destructuring assignment. This way, you can easily get both the index and the element.
Another powerful way to iterate over an array is by using the forEach()
method. Unlike the for...of
loop, forEach()
is not a loop construct but a method that provides a more functional approach to iteration. You pass a function to forEach()
, and it calls that function once for each element in the array.
The forEach()
method iterates over the array in order, just like the for...of
loop. It also passes the array index to the function as a second argument, which can be quite useful in certain situations.
Array.isArray()
A handy feature is the Array.isArray()
method. In JavaScript, it's sometimes tricky to differentiate between arrays and objects because arrays are technically objects. That's where Array.isArray()
comes in—it checks whether a given value is an array and returns true
if it is. This little utility is incredibly useful when you're writing functions that need to handle different types of inputs and you want to ensure you're working with an array.
By understanding these special features, you can leverage the full power of arrays in JavaScript, making your code more robust and easier to maintain.
Moving Forward
We've covered a lot about arrays already! This information is more than enough to earn your blue belt and handle 95% of the scenarios you'll encounter. As you progress to higher levels, we'll dive even deeper into the more advanced aspects of arrays.
Study Style Notes
- Definition: An array is an ordered collection of values (elements), each stored in a sequence with a numeric index.
- Flexibility:
- Untyped: Arrays can store any type of data, and elements can be of different types.
- Zero-Based Index: Arrays start at index 0, with a maximum possible size of over four billion elements.
- Dynamic Size: Arrays can dynamically grow or shrink without needing a fixed size at creation.
- Optimization: JavaScript engines optimize arrays for fast access using numeric indices. ES6 introduced "typed arrays" for more efficient handling of specific data types.
Creating Arrays
- Simplest Method: Use square brackets to define a list of elements.
Reading and Writing Elements
- Accessing Elements: Elements are accessed using square brackets with an index. This allows reading and writing values to specific positions.
- Array Length Property: Automatically updates to reflect the number of elements, which changes when elements are added or removed.
Arrays vs. Objects
- Similarities: Arrays are a type of object, and array indices are treated as string properties internally.
- Differences:
- Array Indexes: Must be non-negative integers within a specific range.
- Object Property Names: Can be any string, not limited to numeric indices.
Adding and Deleting Array Elements
- Adding Elements:
push()
: Adds elements to the end.unshift()
: Adds elements to the beginning.
- Removing Elements:
pop()
: Removes the last element.shift()
: Removes the first element.delete
: Removes an element without affecting the array's length or shifting elements.
Iterating Over Arrays
for...of
Loop: A simple and readable way to loop through each element in an array.- Combining
entries()
withfor...of
: Allows access to both index and value during iteration. forEach()
Method: Provides a functional approach to iterating over arrays by applying a function to each element.
Array Type Checking
Array.isArray()
Method: Determines if a given value is an array, useful for distinguishing arrays from regular objects.
Conclusion
- Importance: Understanding JavaScript arrays is crucial for effective coding. Arrays provide a flexible way to store and manipulate collections of data, supporting a wide range of operations and use cases.
- Best Practices: Knowing the distinctions between arrays and objects, as well as the various methods for adding, removing, and iterating over elements, helps in writing robust JavaScript code and avoiding common pitfalls.