10 Steps to Master JavaScript Array For Beginners
Tags: webdev, beginners, programming, javascript
Published: 2023-07-12 17:51:42

##Table of content
* [Introduction](#intro)
* [What is an array?](#step-1)
* [How to create an array](#step-2)
* [Array index](#step-3)
* [Array properties](#step-4)
* [Unshift element to array](#step-5)
* [Shift an element to an array](#step-6)
* [Push an element to an array](#step-7)
* [Pop an element out of an array](#step-8)
* [Element inclusion in an array](#step-9)
* [Find an element by index](#step-10)
* [Conclusion](#conclusion)

### Introduction <a name ="intro"></a>
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](https://dev.to/momokid/variables-in-programming-17ge) and [function](https://dev.to/momokid/functions-are-dry-25nd)


---

### 1. What is an array <a name='step-1'></a>?
As defined by [mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array);

> 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 <a name="step-2"></a>
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 <a name="step-3"></a>
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;


![Array elements](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hql7gntqhb83cyg29sbs.jpg)

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;

![Array index](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ofnezoaltmt6sl4l91vl.jpg)

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 <a name="step-4"></a>
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 the `length` 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 <a name="step-5"></a>
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;

![before array.push method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3arwtfh0hi4pxkpz17gy.png)

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;


![after prepending array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7z1pwf3mt89jauolr9b.png)

When you prepend an element, the positions/indices of all the existing elements will increase by 1.

### 6. Shift an element to an array <a name="step-6"></a>
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;

![before unshift array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xmxby14664qxil25b58t.png)

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;

![after array shift](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lx3m0hpjbnf3ie1p2yvh.png)

### 7. Push an element to an array <a name="step-7"></a>
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'];

```

![Before array.push()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h8s5ey8g05gqa2kjtgiw.png)

### 8. Pop an element out of array <a name="step-8"></a>
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'];

```

![array.pop books](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bft0tjmoph5gg6jwo2i9.png)


### 9. Element inclusion in an array <a name="step-9"></a>
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 <a name="step-10"></a>
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 <a name="conclusion"></a>
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). 

Thank you for your time. See you on the next one.