A JavaScript Array is a special kind of Object that represents an indexed collection of values.
An array variable is defined with square brackets surrounding a list of values (or no value at all, if the array is empty).
The example below defines an empty array
const myArray = []; console.log(typeof (myArray)); // Expected output: object
Arrays consists of indexed lists of values, known as items. These items are separated by a comma in the array definition, as seen below:
const balls = ['blue', 'purple', 'green', 'yellow'];
In the example above, I have declared const balls to be an array, whereas every item in the array is a string that indicates a ball’s color.
Retrieving a specific value from an array requires you to write the array’s name, followed by square brackets surrounding the index number of the item you wish to retrieve:
console.log(balls[2]); // Expected output: green
In the example above, we retrieve the item in the array at index 2. In JavaScript, array indices start at zero. Thus, the code console.log(balls[2]) above refers to the green ball, which is actually the third item in the array.
When creating an array, you can either create an empty array (as seen in the myArray example above), or you can create an array with items already inside (as seen in the balls example). When declaring an array with items already populated, each item must be separated from the others with a comma.
If you do not use commas to separate items, an array with a single item will be formed, as seen in the example below:
const single = ['Single item array']; console.log(single[0]); // Expected output: Single item array
The Array object’s prototype has several methods that allow you to operate on and manipulate the data in the array.
Below, we’ll walk through a few of the basic array methods. This is not intended to be a comprehensive exploration, but rather just a demonstration of the types of things that can be achieved with arrays.
Adding and removing items
You can add items to either the beginning (left) or the end (right) of an array. To add an item to the beginning of an array, use the unshift() method:
const balls = ['blue', 'purple', 'green', 'yellow']; balls.unshift('red'); console.log(balls); // Expected output: ["red", "blue", "purple", "green", "yellow"]
If you wish to add an item to the end of an array, use the push() method:
balls.push('white'); console.log(balls); // Expected output: ["red", "blue", "purple", "green", "yellow", "white"]
You can similarly remove items from either the beginning or end of the array. To remove an item from the beginning of the array, use the shift() method:
balls.shift(); console.log(balls); // Expected output: ["blue", "purple", "green", "yellow", "white"]
And to remove an item from the end of an array, use the pop() method:
balls.pop(); console.log(balls); // Expected output: ["blue", "purple", "green", "yellow"]
As seen above, through successive use of unshift(), push(), shift(), and pop(), we are able to return the array to its initial value.
Note: the methods to add items – push() and unshift() – can handle multiple values simultaneously, respectively adding items to the end or beginning of an array.
You can add or remove items at a specific index in the array using the splice() method:
balls.splice(2, 0, 'red'); console.log(balls); // Expected output: ["blue", "purple", "red", "green", "yellow"]
Let’s look at splice() in a little more detail
splice() at a glance
Only the first parameter is required to call the splice() method, the rest are optional.
- The first parameter is the index from which to start the operation
- The second parameter is how many items to delete
- The third parameter, and any parameters following, indicate items to be added to the array
In the example above, the operation began at index 2, deleted zero items, and added ‘red’ to the array at index 2.
You can use the length property to retrieve the number of items in a given array:
console.log(balls.length); // Expected output: 4
The length of an empty array will always be zero:
const myArray = []; console.log(myArray.length); // Expected output: 0
One of the most powerful tools offered by arrays is the ability to iteratively apply code to their contents. This allows you to make use of all of the data stored in the array, either individually or in aggregate. There are multiple iteration methods, each with its own intended purpose. While we will not dive deeply into each method, the following can be used as an overview to get a general sense of what each iteration operation is intended to do:
forEach() – allows you to execute a function for each item in the array.
map() – returns a new array after performing an operation on each item of the original array.
filter() – returns a new array with all of the items that match a specified condition.
reduce() – applies operations to an array that reduce the array to a single return value.
findIndex() – allows you to find the index of an item which matches a certain condition.
includes() – returns true if the array contains a specified value.
To determine if a given variable is an array, you can use JavaScript’s provided Array.isArray() method:
console.log(Array.isArray(balls)); // Expected output: true
Note: unlike the former methods, which are called as functions on the Array object, this method requires you to pass in the variable to examine as a parameter. This is because we cannot yet know if the variable is an array, and thus we do not know if it has access to the built in Array methods.
An array can mix different types of values together
const mix = ['Type', 4, ['A', 'B', 'C'], { name: 'Shelly', age: 69 }];
In the example above, while const mix is a valid array and JavaScript gives you the capability to create any mixed array that you like, these types of array are typically not used as they make the code challenging to work with. With mixed arrays, it is difficult to easily understand what types of data are contained in the list of values, and using iteration methods becomes very impractical. As a result, most arrays generally store only one type of value, whether these are Strings, Numbers, Objects, or other Arrays.
Related Articles
JavaScript – How to Search Arrays
JavaScript – How to Use the Array sort() Method
JavaScript – How to Use for Statements