10 most used Javascript Array methods
Published: 2022-12-30 09:35:02

Array is a single variable that is used to store different elements. It is mostly used when we want to store a list of elements and access them, using one variable. Storing elements into an array enables us to perform unique methods and operations on those items.

In Javascript arrays are `Array` objects with the following characteristics:
- Javascript arrays are resizable and can contain a mix of different [data types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures).
- Javascript arrays are zero-indexed, which means that the first item in an array will always have index `0`.
- When using array-copy operations on a javascript array the operation creates a shallow copy. That means that the source and the copy are not completely independent and changing one can cause changes in the other.

To work with arrays methods are used, which enable us to manipulate arrays in different ways. Here are some of the methods that are used on arrays a lot.

## Table of Contents
1. [.push()](#push)
2. [.pop()](#pop)
3. [.unshift()](#unshift)
4. [.shift()](#shift)
5. [.splice()](#splice)
6. [.slice()](#slice)
7. [.concat()](#concat)
8. [.indexOf()](#indexof)
9. [.lastIndexOf()](#lastindexof)
10. [.toString()](#tostring)
   

---

## .push()

`.push()` adds one or more elements to the end of the array and returns the new length of the array.

### Syntax
```js
push(element0, element1, /* … ,*/ elementN)
```

`elementN` -> element/s that will be added to the end of the array

### Examples
```js
// adding elements to the array
const animals = ["dog", "cat"];
const pushedArray = animals.push("fish", "horse");

console.log(animals); 
console.log(pushedArray); 

/*
Expected output:
animals = ["dog", "cat", "fish", "horse"]
pushedArray = 4 -> length of the new array
*/
```

```js
// merging two arrays
const animals = ["dog", "cat"];
const moreAnimals = ["fish", "horse", "hippo"]

const pushed1 = animals.push(moreAnimals)
const pushed2 = animals.push(...moreAnimals)

console.log(pushed1); 
console.log(pushed2); 

/*
Expected output:
pushed1 = ["dog", "cat", ["fish", "horse", "hippo"]]
pushed2 = ["dog", "cat", "fish", "horse", "hippo"]
*/
```

Instead of using `.push()`you can use `.concat()`method to merge two arrays

---

## .pop()

`.pop()` removes the last element of an array. It returns the removed value or `undefined` if the original array has no elements.


### Syntax
```js
pop()
```

### Example
```js
const vegetables = ['broccoli', 'cauliflower', 'cabbage'];

console.log(vegetables.pop())

/*
Expected output:
"broccoli" -> is removed from the original array
2 -> length of the new array
*/

```

---

## .unshift()

`.unshift()` adds one or more elements to the beginning of the array. If multiple elements are passed as parameters, they are inserted at the beginning in the exact same order they were passed as parameters.

### Syntax

```js
unshift(element0, element1, /* … ,*/ elementN)
```
`elementN` -> elements that will be added to the front of the array

### Example

```js
const array = ["My", "name", "is", "Neo", "."]

array.unshift("Hello", "World", "!")

console.log(array)

/*
Expected output: 
["Hello", "World", "!", "My", "name", "is", "Neo", "."]
*/
```

---

## .shift()

`.shift()` removes the first element of an array and returns the removed item. It changes the lenght of the original array. If the original array has no items (length is 0) then the method returns `undefined`.

### Syntax
```js
shift()
```

### Example
```js
const array = ["My", "name", "is", "Neo"]
const firstElement = array.shift()

console.log(array)
console.log(firstElement)

/*
Expected output:
array = ["name", "is", "Neo]
fristElement = ["My"]
*/

```

---

## .splice()

`.splice()` is used to change the contents of an array by removing or replacing elements in the array. Elements can also be added using `.splice()`. This method returns an array containing the deleted elements. If no elements are removed, then an empty array is returned.

### Syntax

```js
splice(start, deleteCount, item1, item2,/*...*/ ,itemN)
```

 `start` -> a zero-based index at witch the methods starts changing the array. If a negative value is used, then the method counts back from the end of the array (if `start < 0` then the array starts changing at `start + array.length`. If this value is omitted than the value `0`is used by the method. If the start walue is bigger than the lenght of the array then nothing will change with the array (no item will be deleted/replaced), but the method will behave as an adding function as many elements as provided.
 `deleteCount` -> an integer indicating the number of elements in the array to remove from `start`. If `deleteCount`is omitted, or it's value is greater than the number of elements from `start`to the end of the array, then all of the elements starting from `start` will be deleted. If the `deleteCount` value is less or the same as `0`, no items will be removed and an `itemN` value should be passed, because an item will be added.
 `itemN` -> element/s added to the array, beginning at `start`

### Examples

```js
//remove 0 elements - insert 2 elements
const animals = ["cat", "fish", "dog", "bird"];
const splicedArray = animals.splice(3, 0, "horse", "elephant");

console.log(splicedArray)

/*
Expected result: 
animals = ["cat", "fish", "dog", "horse", "elephant", "bird"]
Returned value: [] - no items are removed
*/
```

```js
//remove 1 element
const animals = ["cat", "fish", "dog", "bird"];
const splicedArray = animals.splice(2, 1);

console.log(splicedArray)

/*
Expected result: 
animals = ["cat", "fish", "bird"]
Returned value: ["dog"] - removed item at index value 2
*/
```

```js
//remove 1 element - insert 2 elements
const animals = ["cat", "fish", "dog", "bird"];
const splicedArray = animals.splice(2, 1, "horse", "elephant");

console.log(splicedArray)

/*
Expected result: 
animals = ["cat", "fish", "horse", "elephant", "bird"]
Returned value: ["dog"] - removed item at index value 2
*/
```

```js
//remove all elements from specified index
const animals = ["cat", "fish", "dog", "bird"];
const splicedArray = animals.splice(2);

console.log(splicedArray)

/*
Expected result: 
animals = ["cat", "fish"]
Returned value: ["dog", "bird"] 
- removed items from index 2 untill the end
*/
```

---

## .slice()

 `.slice()` returns a shallow copy od a portion of an array, based on the `start` and `end` values specified. The original array is not modified in the process. This method preserves empty slots from the original array.

### Syntax
```js
slice(start, end)
```
Parameters `start` and `end` are both optional.
 `start`-> zero-based index at which the extraction of the elements starts. If `start` value is larger than the length of the array then nothing is extracted.
 `end` -> zero-based index at which the extraction ends. if `end < 0` then `end + array.length` is used. If `end >= array.length` or the `end` is ommited than all of the items from the `start` untill the end of the array are deleted. If `end` is positioned before the `start` then nothing is deleted.

### Example

```js
//return a portion of an existing array

const fruits = ["banana", "apple", "cucumber", "salad", "watermelon"]
const sus = fruits.slice(2,4)

/*
Expected result:
fruits = ["banana", "apple", "cucumber", "salad", "watermelon"]
sus = ["cucumber", "salad"]
*/
```

---

## .concat()

`.concat()` is used to merge multiple arrays. It is a copying method, therefore it does not change the existing arrays, but instead returns a shallow copy, that contains the same elements as the original arrays. It preserves empty slots from the original arrays.

### Syntax
```js
concat(value0, value1, /* … ,*/ valueN)
```
`valueN` -> arrays and/or values to concatinate into a new array. If no `valueN` parameter is specified the method returns a shallow copy of the array on which it is called.

### Examples

```js
// concatinating no arrays
const array = [1,2,3,4,5,6,7,8,9,10]
const concatArray = array.concat()

console.log(concatArray)

/*
Expected output: [1,2,3,4,5,6,7,8,9,10]
*/

```

```js
// concatinating two arrays
const array1 = ["Hello"]
const array2 = ["World", "!"]
const concatArray = array1.concat(array2)

console.log(concatArray)

/*
Expected output: ["Hello", "World", "!"]
*/

```

```js
// concatinating three arrays
const array1 = [1,2,3]
const array2 = ["Hello","World", "!"]
const array3 = [3,2,1]
const concatArray = array1.concat(array2, array3)

console.log(concatArray)

/*
Expected output: [1,2,3,"Hello", "World", "!",3,2,1]
*/

```

---

## .indexOf()

The `indexOf()` method returns the first index at which a given element can be found in the array, or -1 if it is not present. The array is searched from the beginning, starting at `fromIndex`.

### Syntax
```js
indexOf(searchElement, fromIndex)
```

`searchElement`-> element to locate in the array.
`fromIndex` -> zero-based index at which the start of the search for the element begins. The search starts from the beginning of the array and runs to the end or when the element is found.

### Example
```js
const numbers = [1, 6, 3, 5];

numbers.lastIndexOf(1);
numbers.lastIndexOf(3);
numbers.lastIndexOf(7);

/*
Expected result:
numbers.lastIndexOf(1) -> 0
numbers.lastIndexOf(3) -> 2
numbers.lastIndexOf(7) -> -1
*/

```

---

## .lastIndexOf()

The `lastIndexOf()` method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`.

### Syntax
```js
lastIndexOf(searchElement, fromIndex)
```

`searchElement`-> element to locate in the array.
`fromIndex` -> zero-based index at which the start of the search for the element begins. The search starts from the end of the array and runs to the beginning or when the element is found.

### Example
```js
const numbers = [2, 7, 3, 2];

numbers.lastIndexOf(2);
numbers.lastIndexOf(7);
numbers.lastIndexOf(9);

/*
Expected result:
numbers.lastIndexOf(2) -> 3
numbers.lastIndexOf(7) -> 1
numbers.lastIndexOf(9) -> -1
*/


```

---

## .toString()

`.toString()` returns a string representing the elements of the array called on. It calls the `.join()` method internaly, which joins the array abd returns one string containing each array element, separated by commas.

### Syntax

```js
.toString()
```

### Example

```js
const array = [1, "Hello", "my", 2, "name", 3, 4, "is Neo", 5]

console.log(array.toString())

/*
Expected output: "1,Hello,my,2,name,3,4,is Neo,5"
*/
```

---


These are some of the methods used the most when it comes to working with arrays. There are however many more methods, that I did not write about here, but will talk about in the future.