Arrays
Arrays are a special type of variable that can hold multiple values. We already know how to declare variables in JavaScript, so take a look at the example below:
const bestBrand = "Porsche";
const averageBrand = "Toyota";
const notGoodBrand = "Range Rover";
In the example above, we have declared three variables containing brands of cars. But what if you were to declare all the brands of cars in existence today? How many variables would you create? Do you get the picture?
Let's see how you would solve this conundrum using arrays:
const brands = ["Porsche", "Toyota", "Range Rover"];
Above, we have declared an array called brands and set it to hold the three car brands. You even eliminate the deliberate biasness I added when declaring "bestBrand", "averageBrand" and "notGoodBrand", by having one variable name for all the brands.
Note the syntax of an array...it has to be enclosed in square brackets and the values separated with commas.
Arrays are especially useful when you are declaring varibales of the same type. You can take a look at a more advanced example below: Advanced Arrays
How to write arrays
1. Using array literals
We have already seen this method in action in the example above. It is simply declaring a variable name and assigning values to it. Take a look below:
// Example 1
const brands = [];
brands[0] = "Volvo";
brands[1] = "Tesla";
brands[2] = "Man";
brands[3] = "Mercedes";
// Example 2
const brands = ["Volvo", "Tesla", "Man", "Mercedes"];
The two examples above do the exact same thing. However, method one is only used when you don't know the values of your array beforehand, while method two is use when you know the values of your array at the time of declaration.
To better understand Example 1, read more about Accessing the values of an array.
2. Using the new
keyword
The new
keyword is a reserved word in JavaScript, and you can use it to declare an array in the following way:
const myArray = new Array("Porsche", 'Toyota', "Range Rover");
Note that when you use the keyword new
you no longer use square brackets for your array values.
Read more about the new
reserved keyword in JavaScript Reserved Words.
For purposes of readability as well as code execution speed, it is recommended to use the array literal method.
Accessing the values of an array
You can access the values of an array using square brackets, and the index of the item you want to read.
Using the very same example above, if I wanted to access the brand Toyota, I would say:
const brands = ["Porsche", "Toyota", "Range Rover"];
// Our new variable that holds the value we are accessing
const toyota = brands[1];
console.log(toyota);
// Expected result in the console: Toyota
You can also access the values of an array using the at()
method. For example:
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
console.log(fruits.at(2)); // Returns: pear
Read more about the at()
method in Array Methods.
Array Indexing
In the above example, we are accessing the brand Toyota, which, using basic math, is the second item out of three items in our array. So why are we accessing it's value using brands[1]
?
Because arrays are indexed from 0. Meaning JavaScript (and other programming languages) doesn't start counting the number of items of an array from 1...it starts from 0. Therefore, reading the remaining values is as follows:
const porsche = brands[0]; // reads the value Porsche, the first item, index 0
const toyota = brands[1]; // reads the value Toyota, the second item, index 1
const rangeRover = brands[2]; // reads the value Range Rover, the third item, index 2
Arrays are indexed from 0. Therefore, if you want to access the last item, you need to get the length of the array, i.e, the number of items in the array, and then minus one from that value. See the example below:
const brands = ["Porsche", "Toyota", "Range Rover"];
const lastItem = brands.length - 1;
console.log(lastItem); // Expected Result: Range Rover
.length
is an array method that you can read more about in the Array Methods section.
Advanced Arrays
When speaking about advanced arrays, I don't mean arrays that have a degree or anything, but about how you can write arrays that hold much more data than just simple names of car brands.
Usually, when you will be working with APIs, you will find that they are arrays structured using objects. This is called an array of objects, i.e, an array that contains objects as its main value.
For example:
const brands = [
{
name: "Supra",
brand: "Toyota",
weight: {
imperial: 3300,
metric: 1500
},
top_speed: 330,
horsepower: 780,
torque: 1000,
},
{
name: "Lexus",
brand: "Toyota",
weight: {
imperial: 4000,
metric: 1800
},
top_speed: 280,
horsepower: 800,
torque: 920,
},
]
Objects are another type of data structure that are declared using curly brackets in JavaScript. Read more about objects in JavaScript Objects.
Above, we have the same array called brands, but with a slightly different structure. This time, we are using an object, and instead of just giving the brand name, we give the car some values that make it more descriptive such as its weight, top speed, horsepower and torque.
In the above example, you can see that arrays can span multiple lines. This is because whitespaces are ignored when you declare an array.
Converting an Array to a String
Take a look at this example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
You can convert this to a string using the .toString()
method.
console.log(fruits.toString()); // Expected Result: banana,orange,pear,apple,mango
Note that when you convert an array into a string, it returns the array as a comma separated string.
Arrays are Objects
Arrays are considered objects in JavaScript. See the example below:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
console.log(typeof fruits); // Expected Result: object
The typeof operator in JavaScript returns a string indicating the type of the operand's value.
For example:
console.log(typeof 20); // Returns "number"
console.log(typeof "thomas"); // Returns "string"
console.log(typeof true); // Returns "boolean"
console.log(typeof yourArray); // Returns "object"
Array Methods
You can perform a number of functions on any array, ranging from getting the number of items in the array, to sorting the array in some type of order. Below are the common array methods.
length
This is used to get the number of items in an array.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
console.log(fruits.length); // Expected result: 5
In order to get the last element in an array, you use length - 1
. For example:
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
console.log(fruits.length - 1); // Expected result: mango
You can also use the .length
method to append another element to an existing array.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
fruits[fruits.length] = "lemon";
console.log(fruits); // Expected result: ["banan", "orange", "pear", "apple", "mango", "lemon"];
// Lemon is now added to the array
toString
This is used to converted an array into a comma separated list of values.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
console.log(fruits.toString()); // Returns: banana,orange,pear,apple,mango
at
This returns an indexed element from an array.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
console.log(fruits.at(1)); // Returns: orange - because arrays are indexed from 0;
console.log(fruits.at(4)); // Returns: mango
join
Just like the .toString()
method, .join
also joins all array elements into one, with the additional control that you can specify the separator.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
fruits.join(" - ");
console.log(fruits); // Expected Result: banana - orange - pear - apple - mango
shift
This is used to remove the first element of an array.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
fruits.shift();
console.log(fruits); // Expected result: ["orange", "pear", "apple", "mango"]
unshift
This is used to add a new element to the beginning of an array.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
fruits.unshift("pineapple");
console.log(fruits); // Expected result: ["pineapple", "banana", "orange", "pear", "apple", "mango"]
concat
Concat is short for "concatenate" which means "to join stings end to end". Therefore, using the concat
method will join two array elements to one.
For example:
const carBrand = ["BMW M3"];
const carType = ["GTR E46"];
const carName = carBrand.concat(carType);
console.log(carName); // Expected result: BMW M3GTR E46
concat
joins strings without adding a space, hence the result above. You can manually add a space to your string if you already know beforehand how your end string will be.
However, another method, and more preferrable is to use concat
along with the join
method as below:
const carName = carBrand.concat(carType).join(" "); // This joins the strings using a whitespace to improve readability.
console.log(carName); // Expected result: BMW M3 GTR E46
copyWithin
This is used to copy an element in an array to another position in the same array. This does not add a new element to the array. Therefore, the new array will have the same length.
Example 1:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
fruits.copyWithin(2, 0);
console.log(fruits); // Expected result: ["banana", "orange", "banana", "orange"]
The statement fruits.copyWithin(2, 0);
means, copy to index 2 (the third item) of the array, all the elements starting from index 0 (the first item) of the array.
copyWithin
overwrites the existing array while still preserving its length.
Example 2:
const fruits = ["banana", "orange", "pear", "apple", "mango", "pineapple", "lemon"];
fruits.copyWithin(2, 0, 2);
console.log(fruits); // Expected result: ["banana", "orange", "banana", "orange", "mango", "pineapple", "lemon"]
The above means, copy up to index 2 (the third item), all the elements starting from index 0 (the first item) up to index 2 (the third item). Compare the results from Example 2 with the results from Example 1.
flat
This is used to reduce multi-dimensional into one-dimensional arrays.
You can think of multi-dimensional arrays like tables containing rows and columns. Therefore, it is an array of arrays. Below is an example of a multi-dimensional array:
const multiDimArray = [[1, 2], [3, 4], [5, 6]];
A multi-dimensional array is an array of arrays.
When we want to reduce this kind of an array into a one-dimensional array, we use the flat
method as below:
const multiDimArray = [[1, 2], [3, 4], [5, 6]];
multiDimArray.flat();
console.log(multiDimArray); // Expected result: 1,2,3,4,5,6
splice
Just like splicing in English means to join two parts of something, the splice
method will add new items to an array - but can also be used to remove elements from an array.
For example:
// Once again with the fruits example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.splice(2, 0, "Pineapple", "Lemon"));
// Expected result: ["Banana", "Orange", "Pineapple", "Lemon", "Apple", "Mango"]
The above block of code can be interpreted as follows: Begin adding new items from the second index of the array, i.e the third item, without removing any elements from the array, i.e 0.
Take a look at the modified example below in which the splice
method is used to remove items from an array:
// Once again with the fruits example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.splice(2, 2, "Pineapple", "Lemon"));
// Expected result: ["Banana", "Orange", "Pineapple", "Lemon"]
The above means: start adding the items form the second index of the array, and remove 2 trailing elements after the new ones have been added. Therefore, even the new array will change in length.
When using splice
, the first parameter is used to define the position at which the new elements should be added. The second parameter defines how many elements should be removed after the new ones have been added in.
slice
Not to be confused with splice
, the slice
method is used is used to cut out a piece of an array, like a slice of cake.
For example:
// Once again with the fruits example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.slice(2)); // Expected result: ["Apple, Mango"]
The above removes the first and second elements of the array because we have specified the slicing to start from index 2 which is the third element of the array.
slice
can also take in two arguments as follows: slice(1, 3)
. This will return the elements between index 1 (the second item) and index 3 (the fourth item). Therefore, using the example above, you will have something of the sorts:
// Once again with the fruits example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.slice(1, 3)); // Expected result: ["Apple, Mango"]
toSpliced
This is similar to splice
with the difference being that toSpliced
leaves the original array unchanged and then returns a new array with the spliced elements.
For example:
const fruits = ["banana", "orange", "apple", "mango"];
console.log(fruits.toSpliced(0, 2, "pineapple")); // Expected result: ["apple", "mango"]
The above example splices the array from the first element (index 0) to the third element (index 2) and then returns the remaining elements in the array.
sort
This is used to sort an array in alphabetical order.
For example:
const fruits = ["banana", "orange", "apple", "mango"];
console.log(fruits.sort()); // Expected result: ["apple", "banana", "mango", "orange"]
Sorting arrays in JavaScript is a topic of its own which you can read about in Sorting Arrays
map
This is used to loop over the elements of an array and then perform some function on all the elements.
For example:
const numbers = [2, 4, 6, 8];
numbers.map((num) => console.log(num * 2)); // Expected result: 4, 8, 12, 16
map
always returns a new array. Always take that into consideration when you want to loop over many elements in your code.
pop
This removes the last element from an array.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
fruits.pop();
console.log(fruits); // Expected result: ["banana", "orange", "pear", "apple"]
push
This adds an element to the end of an array.
For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
fruits.push("pineapple");
console.log(fruits); // Expected result: ["banana", "orange", "pear", "apple", "mango", "pineapple"]
forEach
This is used to loop over the elements of an array. Using this, you can perform some function that will iterate over all the elements in the array.
For example: the code block below will multiply every element in the array by 2 and then return the new array.
const multiply = [2, 4, 6, 8];
multiply.forEach((number) => console.log(number * 2)); // Returns [4, 8, 12, 16]
isArray
The isArray
method is used to test whether a variable is an array. For example:
const fruits = ["banana", "orange", "pear", "apple", "mango"];
Array.isArray(fruits);
This is because when we use typeof
- which is the recommended way to know what type of value an operand is - to test whether a variable is an array, it returns object
in JavaScript. The isArray
method solves this issue.
The isArray
method also solves another issue that is introduced by new Array()
.
Usually, when you use new Array
to declare an array, you will - most of the time - get the same results...except for one situation. See the example below:
const myArray = [10, 20, 30, 40];
const myArray = new Array(10, 20, 30, 40);
The above will do the exact same thing, that is, to create an array with four elements. However, take a look at the example below:
const myArray = [10];
// Creates an array with one item
const myArray = new Array(10);
// Creates an array containing 10 elements
Above, the array literal will create an array with one item. However, new Array
will create an array with 10 elements! Take note of this.