Table of content
- Introduction
- What is an array?
- How to create an array
- Array index
- Array properties
- Unshift element to array
- Shift an element to an array
- Push an element to an array
- Pop an element out of an array
- Element inclusion in an array
- Find an element by index
- Conclusion
Introduction
As a programmer, you will always work with data. With small projects such as hello word
and adding two numbers
, you can use primitive variables. But to store the details of an object, like a student, with the first name, last name, address, age, gender, etc, you will need a data structure, and that is where array comes in.
To follow along, you must have basic knowledge of variable and function. Read my previous post on variable and function
1. What is an array ?
As defined by mdn;
The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name and has members for performing common array operations.
Ok, let's break this down.
When collecting related data, you do not need to create multiple variables but rather you need an array to store those data as shown below;
// Using variables to store a student's info
let studentFirstName = "John";
let studentSecondName = "Smith";
let studentAddress="123 Central Park Square, NY";
let studentAge = 18;
let studentGender = "Male";
// Using an array to store a student's info
const studentProfile = ["John","Smith","123 New Address",18,"Male"];
From the above code, we used 5 variables for each data about the student while with the array, we only used the studentProfile array.
2. How to create an array
It is a common practice to use the const
keyword to create an array followed by the name of the array, equal sign, and open and close square brackets as below;
//create an array of 3 books
const books = ['Eloquent Javascript','Head First Javascript Programming','Who Moved My Cheese'];
The elements in an array are separated by a comma. When an element of an array is a string, it is either in single quotes or double quotes.
const
variable does not allow changes to the variable but with const
array, there are methods that you can use to edit the array.
3. Array index
Before we discuss array methods, let's take a look at the array index.
Elements in arrays are stored in a contiguous and sequential order and the elements do not have to be of the same type. Let's take for example the books
array as illustrated below;
The first element is the Eloquent Javascript, the second element is Head First Javascript and the third element Who Moved My Cheese.
Array index is a non-negative integer that is used to access elements in an array. Generally, array index starts at zero (0). Yes, you read it right, zero (0). It means the position of the first element in an array is at index 0
hence referred to as zero-indexed
as illustrated below;
The first element, Eloquent Javascript is at index 0
, the second element, Head First Javascript is at index 1
and the third element is at index 2
.
The index of an element in array = position - 1. e.g. our third _element has an index of 2
. The highest index in an array = array length minus 1. Our books
array has length of 3
and the last element i.e. _Who Moved My Cheese has an index of 2
.
Just for this article, we will use the index to access the elements of our arrays as shown below;
array[index];
//to display the first element in the books array
console.log(books[0]) //output: 'Head First Javascript'
4. Array properties
Every variable type comes with it's own properties in Javascript. A string variable has toLowerCase()
, toUpperCase()
, length
, etc. properties while a number variable has the toString()
, toFixed()
, toPrecision
, etc. properties.
Javascript arrays have the ;
length
property which returns the number of elements in an array.constructor
property returns the constructor function that created the array object.prototype
property allows for adding user-defined properties and methods.
Note that for the purpose of this article, we will discuss thelength
property.
Using our books
array, we can get the size of the elements of the array by the following code;
console.log(books.length) //output: 3
Assuming we want to check if a user has read 3 books, we write our code as;
//check if books read is less than 3
if(books.length < 3){
console.log('You need to read 3 books')
}else{
console.log('Congratulations')
}
//output: 'Congratulations'
The output will be congratulations since the number of elements in the array is 3
.
5. Unshift element to an array
To add an element to the existing elements in our books
array, we use the Array.prototype.unshift()
. The unshift()
method takes a value an insert it at the beginning of the array and returns the new array.
The books
array currently looks like this;
Let's add a new book to the books
array;
//add a new book to the front of books array
books.unshift('Responsive Javascript')
//display all books
console.log(books) //output: Array(4) [ 'Responsive Javascript', 'Eloquent Javascript','Head First Javascript Programming','Who Moved My Cheese' ];
The books
array will now looks like this;
When you prepend an element, the positions/indices of all the existing elements will increase by 1.
6. Shift an element to an array
To remove the first element which is at index 0
in an array, we use the Array.prototype.shift()
method. The shift()
method will remove the first element and return the removed element.
The books
array looks like this;
Let's write the code to remove the last book in the books
array;
//remove the 'Responsive Javascript' book
books.shift()
The books
array will now look like this;
7. Push an element to an array
Just as we added an element at the beginning, we can also add an element at the end of the array. The Array.prototype.push()
method adds an element to the tail of an array and returns the length of the array.
Let's push()
a new book, Out Of The Maze , to our books
array;
//add element to the end of an array
books.push('Out Of The Maze')
console.log(books) //output: Array(4) ['Eloquent Javascript','Head First Javascript Programming','Who Moved My Cheese','Out Of The Maze'];
8. Pop an element out of array
The Array.prototype.pop()
removes an element at the end of an array and returns the element. This operation does not affect the index of the existing elements.
Let's remove the book we previously added to the books
array;
//show all books
console.log(books) // output: Array(4) ['Eloquent Javascript','Head First Javascript Programming','Who Moved My Cheese','Out Of The Maze'];
//remove 'Out Of The Maze' from books
books.pop();
//show all books after the pop() method
console.log(books) //output: Array(4) ['Eloquent Javascript','Head First Javascript Programming','Who Moved My Cheese'];
9. Element inclusion in an array
Imagine having a dictionary app that you can search for a word without flipping through pages like the "paper" dictionary. Having the search feature makes life easy for your users.
Array.prototype.includes()
feature offers the opportunity to implement a "search" feature in your app by passing the search keyword as a parameter to the includes()
. The method returns true
if the keyword, which uses strict equality (===), exists in the array.
Let's write code to experiment with the "search feature";
//
let searchKeyword = 'Who Moved My Cheese';
//check if keyword includes in books array
let result = books.includes(searchKeyword);
if(result){
console.log(`${searchKeyword} exists in book collection`)
}else{
console.warn('Book does not exists');
}
10. Find an element by index
Elements in an array can be located by their indices by using the Array.prototype.at()
method which takes an integer value and returns the element at that index. It allows for both positive and negative integers. When using negative integers, counting start from the last element in the array.
// get the book at index 2
console.log(books.at(2)); //output: "Head First Javascript Programming"
Conclusion
There are dozens of array methods in Javascript you can use to manipulate elements in an array, Arrays are used in a lot of areas in software development especially fetching data from an API or database. Go ahead and read more on Arrays at mdn.
Thank you for your time. See you on the next one.
Top comments (2)
It is well written. I enjoyed reading your article. Thanks for sharing.
Thank you