If you’re planning on advancing your JavaScript project beyond the simple "hello world"
output, you will need to use arrays.
In this article we’ll cover what an array is, how to create one and what you can do with it. Let’s get started!
What is an array?
In JavaScript, an array (also know as list or vector in other languages) is an ordered list of values. By ordered, I mean each element is placed in a certain position (known as indexes).
A key feature that JavaScript arrays support is that you can store data of different types in the same array (more on this later). For example, you can have String
, Boolean
and Number
elements in the same array. Additionally, arrays are dynamically sized, so you never have to manually increase the size of your array.
In other languages, such as C, you can only store data of the same type in your array, and you have to know the size of the array when creating it.
Now let’s look at some code!
How to create an array?
We can create arrays in two different ways; using the array literal notation or the Array()
constructor.
The most common (and recommended) way of creating an array is to use the array literal notation.
const fruits = [];
This creates the empty fruits
array.
You can also create an array with elements already inside it.
const fruits = ["apple", "pear", "banana"];
The less common way is using the Array()
constructor.
const fruits = new Array();
This creates a new empty fruits
array.
const fruits = new Array(10);
This array is initialised with 10 undefined
elements.
Creating an array with elements already inside it is also possible.
const fruits = new Array("apple", "pear", "banana");
You’ll most likely find yourself never, or rarely, using the Array()
constructor.
What types of elements can I store in JavaScript arrays?
In JavaScript you can store any type of element in your array, and you can even mix types.
const fruits = ["apple", 2, "pear", true, false, ["another", "array", 99]];
This can quickly get messy, so I strongly recommend you use one element type per array!
Why is this possible? If you’re just getting started with programming or JavaScript it’s not important to know this, so feel free to skip this section.
JavaScript is dynamically typed which means variables are assigned its type at runtime. Compared to other programming languages that are statically typed, where the variables types are assigned at compile time.
In other words, dynamically typed languages check the types after running the code and statically typed languages check the types before running the code.
How to read elements of an array?
Remember that arrays in JavaScript are ordered, where each position in the array is represented by a number. This number is usually referred to as the index. And in JavaScript arrays are zero-based indexed, which means the first element of the list has index 0
, the second has index 1
and so on.
If you know the index of the element you want to read, you can simply do this
array[index]
Let’s look at some actual code:
const fruits = ["apple", "pear", "banana"];
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "pear"
console.log(fruits[2]); // "banana"
How to update values in an array?
In JavaScript arrays are mutable, which means they can be updated even after they were created. In comparison to immutable types, such as the primitive types String
and Number
.
Let’s see how we can update the apple
to an orange
in our fruits array.
const fruits = ["apple", "pear", "banana"];
console.log(fruits[0]); // "apple"
// overwrite the element at index 0 with the value "orange"
fruits[0] = "orange";
console.log(fruits[0]); // "orange"
Next we’ll look at how to perform operations such as iterating, adding more elements and more.
How to perform basic operations on arrays?
Where to start? There are many operations you can do with arrays. This section covers the most useful operations.
Add an element to the start
To add an element to the start we use unshift()
.
const fruits = ["apple", "pear", "banana"];
fruits.unshift("orange");
console.log(fruits);
// ['orange', 'apple', 'pear', 'banana']
Add an element to the end
We use push()
to add an element to the end of the array.
const fruits = ["apple", "pear", "banana"];
fruits.push("orange");
console.log(fruits);
// ["apple", "pear", "banana", "orange"]
Remove an element from the start
To remove an element from the start of an array we use shift()
. This method does two things: returns the “shifted” element and removes it from the array.
const fruits = ["apple", "pear", "banana"];
const poppedFruit = fruits.pop();
console.log(poppedFruit); // "apple"
console.log(fruits);
// ["pear", "banana"];
Remove an element from the end
We use pop()
to “pop” the last element from the array. This does two things: returns the “popped” element and removes it from the array.
const fruits = ["apple", "pear", "banana"];
const poppedFruit = fruits.pop();
console.log(poppedFruit); // "banana"
console.log(fruits);
// ["apple", "pear"];
Remove a specific element
There are many ways to do this (like with many things in programming). Let’s look at the two most common ways.
Using filter()
The filter()
function will filter out elements that matches your condition. In this example we say “filter out all elements that are not equals to apple“. filter()
creates a new array instead of changing the original one.
const fruits = ["apple", "pear", "banana"];
const fruitsWithoutApples = fruits.filter(fruit => fruit !== "apple");
console.log(fruitsWithoutApples);
// ["pear", "banana"]
filter()
follows the functional programming principal of never mutating state and can be found in many programming languages (Java, Python, Rust etc.)
Using indexOf() and splice()
If you’re okay with mutating state (updating the array) then we can use the combination of the functions indexOf()
and splice()
to remove a specific element.
In this example, let’s remove the "pear"
string.
const fruits = ["apple", "pear", "banana"];
const pearIndex = fruits.indexOf("pear"); // 1
fruits.splice(pearIndex, 1); // second parameter represents how many elements to remove
console.log(fruits);
// ["apple", "banana"];
Check if array contains specific element
It can be useful to check if an array contains a specific element. Let’s look at some different options.
Using indexOf()
We’re already familiar with indexOf()
at this point. If the element you’re looking for is not in the array, it will return -1
.
const fruits = ["apple", "pear", "banana"];
const orangeIndex = fruits.indexOf("orange"); // "orange" is not in array so -1 is returned
if (orangeIndex === -1) {
// "orange" is not in array
} else {
// "orange" is in array
}
Using includes()
The more straight forward approach is using includes()
which returns a Boolean
.
const fruits = ["apple", "pear", "banana"];
const isAppleInArray = fruits.includes("apple"); // true
Check if variable is an array
In all modern browsers you can use Array.isArray()
to determine if a variable is an array.
const fruits = ["apple", "pear", "banana"];
Array.isArray(fruits); // true
Array.isArray("orange"); // false
Array.isArray(99); // false
Conclusion
Arrays in JavaScript are similar to array / list / vector implementations in other languages. Of course it comes with its own quirks and features, some which are good to be aware of.
Follow me on Twitter @prplcode
Originally published at https://prplcode.dev
Top comments (0)