You can skip to a specific section of this tutorial using the table of contents below:
- How to Access Items From Within an Array
- How to Determine the Length of an Array
- How to Prevent Mutable Array Methods From Mutating Your Arrays
- Final Thoughts
- More arrays (these are called
Here are a few other pieces of array terminology that you should be aware of before proceeding:
- If you're using strict terminology, every element within an array is called an
item(although people will know what you mean if you say
- The location of an item within an array is called its
- The number of items within an array is called the
lengthof the array
var keywords followed by a variable name and the
= assignment operator.
= operator, you need to specify the array's items inside of square brackets. As an example, here is how you could create an array called
integers that contains the first 4 non-zero integers:
const integers = [1, 2, 3, 4];
As you can see, the syntax for creating an array is fairly simple. The items are separated by commas and all the items are wrapped in square brackets.
As mentioned, arrays do not need to specifically contain numbers. They can contain other data structures too.
const names = ['Nick', 'McCullum'];
Just as we used square brackets to create our arrays earlier, we can also use square brackets to access items within an array. To do this, we simply need to pass the variable name and the item's index into
const integers = [1, 2, 3, 4]; const names = ['Nick', 'McCullum']; console.log(integers); //Logs 1 to the console console.log(names); //Logs 'McCullum' to the console
0, the second item of an array will have index
1, and so on.
length of an array is equal to the number of items that the array contains.
The arrays that we have worked with so far have been small enough that we can easily determine their length using the eyeball test. It's obvious as first glance that
integers contains 4 items and
names contains 2 items:
const integers = [1, 2, 3, 4]; const names = ['Nick', 'McCullum'];
When working with larger arrays, however, it's not so easy to determine their length.
length that solves this problem by allowing us to easily determine the length of the array. For example, here's how you could calculate the length of the
integers.length; //Returns 4 names.length; //Returns 2
Accessing the first item of an array is easy - you can simply pass in the index
Many languages allow you to pass in an index of
What is the solution?
array.length - 1.
Here are two examples of how you could use this strategy to access the last item of our
integers[integers.length-1]; //Returns 4 names[names.length-1]; //Returns McCullum
- Mutable array methods perform some sort of mutation to the array. Said differently, the array will be fundamentally different after the method is run.
- Immutable array methods do not change the original array, but they do return a different array that has been modified in some way.
If this is not completely clear, do not worry - we will see many examples in the rest of this tutorial.
push that allow us to easily add items to the end of an array. The
push method takes a single argument - the item that is to be added to the array.
push method to add
5 to the end of our
integers.push(5); console.log(integers); //Logs [1, 2, 3, 4, 5] to the console
Since the purpose of the
push method is to add items to the end of an existing array, then it goes without saying that
push is a mutable array method.
unshift method is a close contemporary of the
push method but instead of adding the item to the end of the array, it adds it to the beginning of the array.
Here's how you could use the
unshift method to add
0 to the start of our recently-modified
integers.unshift(0); console.log(integers); //Logs [0, 1, 2, 3, 4, 5] to the console
push, since the purpose of the
unshift method is to add items to the start of an existing array, then it goes without saying that
unshift is a mutable array method.
Here is an example of how we could use the
reverse method to reverse the order of the items with our
const reversedNames = names.reverse()
If you log this new
reversedNames variable to the console, here is what it prints:
Note that since the
reverse method is a mutable array method, then the original
names array has also been altered:
console.log(names); //Logs ["McCullum", "Nick"] to the console
slice array method is an immutable method that allows you to take a portion of an existing array and assign it to a new array. The
slice method takes two arguments:
begin: the first index of the new array
end: the last index of the new array. Note that the item at this index is not included in the new array.
To see the
slice method in action, let's use our
integers array from earlier in this tutorial.
const middleIntegers = integers.slice(1,3); console.log(middleIntegers); //Returns [2, 3]
Note that since the
slice method is immutable, the original
integers array remains unchanged.
slice method. The only two differences are:
splicemethod is mutable - which means that it actually modifies the value of the array that it is performed on.
- Instead of taking
endas its second argument, it takes
count- which is the number of items of the original array that you'd like to splice from the array.
splice methods are similar enough that
splice does not require any further explanation.
Fair warning, though - the similarity of these methods is bound to introduce bugs in your code at some point, and being aware of how they're related is very useful for debugging purposes.
... operator (pronounced as the
spread operator) along with the
To see this in action, let's again consider our
const integers = [1, 2, 3, 4];
Here's how you would add the item
2.5 between the item
2 and the item
const integersAndDecimals = [ ...integers.slice(0, 2), 2.5, ...integers.slice(2) ]; console.log(integersAndDecimals); //Logs [1, 2, 2.5, 3, 4] to the console
Fortunately, we can again combine the spread operator with the
slice method to build a workaround. Here's how we would remove the item
2.5 from the following array:
const halfSteps = [1, 1.5, 2, 2.5, 3, 3.5]; const halfSteps2 = [ ...halfSteps.slice(0,3), ...halfSteps.slice(4) ]; console.log(halfSteps2); //Logs [1, 1.5, 2, 3, 3.5] to the console
There are certain situations in which you might want to use a mutable array method, but want to avoid having the mutation applied to your original array.
Fortunately, there is a workaround. To avoid the mtuation, you simply need to create a copy of the original array.
The easiest way to do this is by using the
... operator, often called the
spread operator. Here's how we could use this operator to take a copy of the
integers array and then apply the
reverse method to the copied array:
const integers = [1, 2, 3, 4]; const integersCopy = [...integers]; const integersCopyReverse = integersCopy.reverse(); console.log(integers); //Logs [1, 2, 3, 4] to the console console.log(integersCopy); //Logs [4, 3, 2, 1] to the console console.log(integersCopyReverse); //Logs [4, 3, 2, 1] to the console
Notice that while the
integersCopyReverse variables have both been reversed, the original
integers variable remains unchanged.
Note that this could also be done in one line, like this:
const integers = [1, 2, 3, 4]; const integersReversed = [...integers].reverse();
This version is arguably more readable, but seeing multiple steps can be helpful for education's sake.
Here is a brief summary of what you learned:
lengthattribute via the dot operator
- How to access the last element of an array by using the index
array.length - 1
- How to use the