Introduction
JavaScript arrays are variable which can hold more than one value or items of different data types under a single variable name. An array can contain a mixture of numbers, strings and any other JavaScript data types like objects, booleans and even null. You can think of JavaScript array as a big container that helps us to hold different household items.
Much like how you can organize, manipulate, and transform household items, JavaScript arrays allow you to manage data items efficiently. You can easily access, modify, and rearrange the items stored within an array. This ability to work with arrays empowers JavaScript developers to handle data in a structured and dynamic manner, making arrays a fundamental tool in JavaScript programming.
Understanding Arrays
When we have list of items, let's say a list of fruits, storing the items in a regular (scalar) variable will look something like this:
Here comes the problem: if the list of fruits we are having is in hundreds, managing the list of fruit will become daunting and complicated. Storing items in a regular variable does not give us the ability to store different data types as well, thereby limiting the types of items that can be stored in it.
Arrays give us the privilege to store the list of fruit under a single variable name, making it easy for us to to access and manipulate the items. Storing the fruit items will look something like this:
Arrays also give us the ability to store different data-types (including arrays themselves) under a single variable name.
Creating Arrays
There are two methods used to create an array:
-
Constructor method
-
Array Literals
The syntax is:
Most of the time, the second method and syntax are used. Throughout this article, we will be making use of the second syntax.
An array that doesn't have any items in it is said to be an empty array. In the code sample above, we've only created an empty array, because we have not supplied any item into the square brackets and the constructor method. We can add items to the array by entering a list of items we want between the square brackets separated by a commas.
You can supply a trailing comma after the last item in the list.
Array indexing and Accessing Elements
When we create an array the element positions start from index of zero. We count the array items from zero up to the last item in the list.
The position number is often referred to as the index number.
We can access each element in the array using the [ ]
notation along with the index number. This is achieved by inserting the index number within the square brackets.
Syntax:
The square brackets and the index number can also be used to change an element in the array. Similarly, they can be used to add a new element to the array.
In example above, we access the second element in the array with the index number [1]
and we assign a new element the position.
In the second part of the code, we try to access the fourth element in the array which was not there, then immediately we assign an element to it. The position index [3]
is created by JavaScript, and the element Mango
is inserted into the list, taking up the fourth position.
Accessing an index that is not in the array will return
undefined
.
Array Length and Manipulation
To get the length of an array, we can can use the length
property on the array variable. This property returns an integer number signifying the length of the array (the number of elements in the array).
Accessing the last element in the array: We can obtain the last index element in the using the length property
The length properties is equally writable; we can increase and decrease it by assigning a new value to it. If we increase the length, an empty items
will be created. Accessing this empty items
will return undefined
. Conversely, if we decrease the length, the array will be truncated. The process is irreversible.
JavaScript provides different ways to manipulate array elements:
-
Using array methods such as
pop
,push
,shift
,unshift
among others. -
Updating elements by directly assigning new values. (as discussed in the previous section).
In the subsequent section, we will be discussing the various array methods provided by JavaScript.
Looping through Arrays
There are situations where we need to iterate through all the items in an array. Attempting to access all the items in an array using direct index numbers can be tedious and time-consuming. JavaScript provides us with ways to go through all the items in an array, which includes: for
loop and the for...of
loop
For Loop
You can use for
loop to iterate over the elements of an array. It allows you to perform operations on each element in the array. Here is a basic example of how you can use a for
loop to iterate over the elements of an array:
In this example, the loop iterates through each element in the array. The loop control count variable i
is used as an index to access each item in the array using fruits[i]
.
The loop terminates when i
equals to the length
of the array ensuring all the items are iterated over.
For...of Loop
for...of
loop is a modern approach to iterates over the element in an array. It is concise and readable, making it more preferable than the traditional for
loop.
In the example, the for...of
loop iterates over each element in the fruits
array. During each iteration, the value of the current element is assigned to the loop variable fruit
, and the loop body is executed. The loop automatically handles the index and provides direct access to the element
The for...of
loop abstracts away the need for maintaining an index and provides a clean and straightforward way to work with iterable objects like arrays, strings and more. It is especially useful when you're more interested in the values themselves rather than the index for your operations.
Array Methods
JavaScript provides us with various predefined actions that can be performed on arrays. In this this section, we will be looking at most important arrays methods.
push()
:
-
Adds one or more elements to the end of an array.
-
Returns the new length of the array.
pop()
:
-
Removes the last element from the end of an array.
-
Returns the removed element.
unshift()
:
-
Adds one or more elements to the beginning of an array.
-
Returns the new length of the array.
shift()
:
-
Remove element from the beginning of an array.
-
Returns the removed element.
splice()
:
-
Allows you to add, remove, or replace elements in an array at a specific index.
-
Modifies the original array and returns an array containing the removed elements (if any).
You can read more on splice() MDN
concat()
:
-
Creates a new array by combining the elements of one or more arrays.
-
Does not modify the original arrays
slice()
:
-
The
slice()
method is used to extract a portion of an array and return a new array containing the selected elements. -
Does not modify the original array
Read more on
slice()
MDN
Iteration Method
Iteration methods help us to perform repeated specific action or operation on sequence of elements. This methods allow us to perform some certain actions until a condition is met.
We will be discussing some of the most important iteration methods provided by JavaScript.
forEach()
:
The forEach
method executes a provided function once for each array element. It does not create a new array.
forEach()
returnsundefined
map()
:
The map()
method creates a new array with the results of calling a provided function on every element in the array.
filter()
:
The filter()
method creates a new array with all elements that pass a provided test function.
reduce()
:
The reduce()
method applies a function against an accumulator and each element in the array to reduce it to single value.
some()
and every()
:
-
some()
tests whether at least one element in the array passes the test. Returns a boolean value. -
every()
tests whether all elements in the array pass the test. Returns a boolean value.
All the iteration methods discussed above help you to achieve tasks more elegantly with less boilerplate code. The are also more functional in nature, which aligns with modern programming paradigms.
Multidimensional Array
JavaScript support multidimensional array such as 2D and 3D arrays. Multidimensional array is an array that contains another arrays within it. Multidimensional arrays forms a grid-like structure (matrix) which can be used for data representation. Here is a representation of 2D and 3D array
It's important to note that excessively deep nesting can lead to code that is difficult to understand and maintain. It can also have performance implications, as accessing deeply nested elements might become inefficient. In most cases, if you find yourself needing very deep nesting, it might be worth considering alternative data structures or rethinking your data organization to keep your code manageable. For practical purposes, most use case involve array with 2 or 3 level of nesting (2D or 3D arrays).
Using Spread Operator with Arrays
The JavaScript spread operator ...
is a versatile syntax introduced in ES6 (ECMAScript 2015) that allows you to expand an iterable into individual elements.
Iterables are objects you can iterates over using the
for...of
loop syntax
How the spread operator works with Array
- Copying Array:
You can use the spread operator to create a shallow copy of an existing array, without modifying the original one.
- Merging Arrays:
The spread operator can be use to merge multiple arrays into single array.
- Passing Function Arguments:
The spread operator can be use to pass elements into a function an individual arguments. Each element in the array is represented an argument in the function.
- Adding Element to an Array:
You can add elements to anywhere in an existing array, without modifying the existing array.
Summary
In this article we discussed what JavaScript arrays are and how they can be useful. We compared them with regular variable declarations and how they can hold values of different data types.
We covered how array can be created and using both the literal and constructor methods, providing code samples for each method. We discussed how we can access array elements using index numbers and how we can assign new values to array elements using index numbers, with code samples. We also took some time to look into one of the most important array property length
, and how it can be used to manipulate arrays and retrieve the length of an array.
We touched on some of the most important JavaScript array methods, such as push
, pop
, shift
, unshift
, map
. We dig into , among others, with code examples on each method. Later in the article, we delved into how to iterate over array element and how we can perform actions on each array element using the iteration functions. We explored how multidimensional arrays can be useful for data storage, by having arrays inside other arrays.
Lastly, we discuss on how the spread operator can be incredibly useful when working with arrays.
Conclusion
JavaScript developers use JavaScript arrays almost every day in their development process. So understanding the applications and how they can be used can help you in your development work. When working with arrays, it's important to avoid common pitfalls such as accessing elements with wrong index, avoiding infinite loops, and using array methods appropriately for the task at hand.
You can also continue your learning by exploring other array methods that weren't covered in this article or by checking out the MDN documentation for more in-depth information on arrays.