Javascript Array Methods – Easy Examples That Make Learning A Blast
Tags: javascript, webdev, beginners, programming
Published: 2024-07-10 15:12:26

Whether you are learning Javascript for the first time or you are an experienced developer, chances are you will be working with arrays frequently. This post was created to help you understand (or remind you of) how the most common Javascript array methods work. We recommend bookmarking this post, as it will be helpful more often than you might expect.

In addition to briefly explaining each method and providing relevant examples, we have also included the .length property since it’s also commonly used.

All Javascript array methods described in this post have been organized in alphabetical order to make searching easier. For those who want to learn more, we’ve also included a link to the MDN documentation in the footer of each code snippet for quick access to detailed information about the related method.

For any beginner developers who have just started their journey, seeing `.prototype.` in the name of every method might be confusing. I have to say, in my first steps, it confused me a lot, thinking, “Why not just say `Array.every` instead of `Array.prototype.every`” ? A quick and short explanation to help you move forward without getting stuck is that when we write `Array.prototype.<method_name>` it indicates that the method described exists natively within every array instance (within every array you use).

## Array.prototype.every()
**When to choose this**: When you are checking if **every** element of an array passes a specific condition.
**Returns**: `true` or `false`

```javascript
[🦊, 🐻, 🐼].every(element => element === 🐼);

// false



[🐻, 🐻, 🐻].every(element => element === 🐻);

// true
```

[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every)

**Callback params**

1. `element` – the element checked in each step
2. `index` – the element’s index (its position)
3. `array` – the array itself, to which you have called `.every`

## Array.prototype.filter()

**When to choose this**: The Javascript array filter method is probably one of the most used ones. Use it when you want to create a new array with elements that pass a specific condition.
**Returns**: **A new array**, including the elements that **passed** the condition.

```javascript
[🦊, 🐻, 🐼].filter(element => element !== 🐼);

// [🦊, 🐻]

 
 
[🐻, 🐻, 🐻].filter(element => element === 🐼);

// []

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

**Callback params**

1. `element` – the element checked in each step
2. `index` – the element’s index (its position)
3. `array` – the array itself, to which you have called `.filter`

**Warning**
When a method returns a new array, it is not 100% independent from its source array. It’s a [shallow](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) copy! Proceed with extra caution on this because you might see some unexpected surprises!

## Array.prototype.find()
**When to choose this**: When trying to find the **first** element in an array that passes a specific condition.
**Returns**: The element that passes the condition or `undefined` if no element is found.

```javascript
[🦊, 🐻, 🐼].find(element => element === 🐼);

// 🐼



[🐼, 🐻, 🐼].find(element => element === 🐼);

// 🐼 (The first one)

 
 
[🐻, 🐻, 🐻].find(element => element === 🐼);

// undefined

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)

**Callback params**

1. `element` – the element checked in each step
2. `index` – the element’s index (its position)
3. `array` – the array itself, to which you have called `.find`


## Array.prototype.flat()
**When to choose this**: When you have complex array structures (arrays in arrays), and you want to flatten everything into one level.
**Returns**: **A new array** containing all elements from different array levels.

```javascript
[🐻, 🐻, 🐻].flat();

// [🐻, 🐻, 🐻]



[🐻, 🐻, 🐼, [🦊, [🐻, 🐻], 🦊]].flat();

// default level is 1

// [🐻, 🐻, 🐼, 🦊, [🐻, 🐻], 🦊]



[🐻, 🐻, 🐼, [🦊, [🐻], 🦊]].flat(Infinity);

// Infinity will flatten all levels

// [🐻, 🐻, 🐼, 🦊, 🐻, 🦊]
```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)

(Remember, the new array is a [shallow](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) copy of the source one).

## Array.prototype.forEach()
**When to choose this**: When you need to iterate through every element of an array and perform a specific action **on each** element.
**Returns**: `undefined`

```javascript
[🐻, 🐻, 🐼].forEach(element => {
   
   // check something about this element
   
   isAnimalCarnivore(element);
  
});

// undefined

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)

**Callback params**

1. `element` – the element checked in each step
2. `index` – the element’s index (its position)
3. `array` – the array itself, to which you have called `.forEach`

Since this method always returns `undefined`, if you want your loop to return something, you might want to check the `.map` method.

Warning: This method doesn’t break the iteration unless you throw an Error!


## Array.prototype.includes()
**When to choose this**: When you want to see if a Javascript array contains a specific element.
**Returns**: `true` or `false`

```javascript
[🦊, 🐻, 🐼].includes(🐻);

// true



[🦊, 🐻, 🐼].includes(🐸);

// false
```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)

When working with objects, keep in mind that something like this 👇 won’t work:

```javascript
[{ name: 'Bob' }].includes({ name: 'Bob' });

// false

```
What you need is probably `.some`, `.filter`, or maybe `.find`.

## Array.prototype.length
**When to choose this**: When you want to know/check the length of an array.
**Returns**: A number – The array’s length.

```javascript
[🦊, 🐻, 🐼].length;

// 3



[].length;

// 0

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)

This is a property, not a method. Don’t invoke it.

## Array.prototype.map()
**When to choose this**: When you want to create a new array where each element is transformed by applying a callback function to each element of the original array.
**Returns**: **A new array** containing the transformed elements based on the callback function.

```javascript
[🦊, 🐻, 🐼].map((element, index) => ({

 id: index, animalIcon: element

}));


/* 
   [
     { id: 0, animalIcon: 🦊 },
     
     { id: 1, animalIcon: 🐻 },
     
     { id: 2, animalIcon: 🐼 }
   ]
   
*/ 

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)

**Callback params**

1. `element` – the element checked in each step
2. `index` – the element’s index (its position)
3. `array` – the array itself, to which you have called `.map`


## Array.prototype.pop()
**When to choose this**: When you want to throw away the last item of the array.
**Returns**: The item you threw, or `undefined` if the array was already empty.

```javascript
[🦊, 🐻, 🐼].pop();

// 🐼



[].pop();

// undefined

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop)

The opposite method of `.pop` is `.shift`.

## Array.prototype.push()
**When to choose this**: When you want to add an element (or more than one) to the end of your array.
**Returns**: **The new array’s length**. The method **modifies the original array** by adding any passed element(s) to its end.

```javascript
[🦊, 🐻, 🐼].push(🦊);

// returns 4

// [🦊, 🐻, 🐼, 🦊];



[🦊, 🐻, 🐼].push(🦊, 🦊, 🦊);

// returns 6

// [🦊, 🐻, 🐼, 🦊, 🦊, 🦊];

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)

## Array.prototype.reduce()
**When to choose this**: When you want to condense an array into a single value based on some logic applied by the callback function. E.g., when you want to calculate a sum or an average.
**Returns**: A single value as a result of applying the callback function to each element of the array.

```javascript

[1, 2, 1].reduce((acc, element) => acc + element)

// 4



[1, 2, 1].reduce((acc, element) => acc + element, 10)

// 14 (accumulator - initial value - set to 10)
```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)

**Callback params**

1. `accumulator` - What is returned by the callback function. The default value of an accumulator, if not specified otherwise, is 0
2. `element` - the iteration's element
3. `index` - the element's index position

## Array.prototype.reverse()
**When to choose this**: When you want to reverse the order of the array’s elements.
**Returns**: The **original** array reversed.

```javascript
[🦊, 🐻, 🐼].reverse();

// [🐼, 🐻, 🦊];
```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse)

## Array.prototype.shift()
**When to choose this**: When you want to throw away the first item of the array.
**Returns**: The item you threw, or `undefined` if the array was already empty.

```javascript
[🦊, 🐻, 🐼].shift();

// 🦊



[].shift();

// undefined

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)

The opposite method of `.shift` is the `.pop` method.


## Array.prototype.slice()
**When to choose this**: When you want a slice 🍕 of an array.
**Returns**: The slice you asked for in **a new array**.

```javascript
[🦊, 🐻, 🐼, 🐸, 🐯, 🦝].slice();

// returns slice

// [🦊, 🐻, 🐼, 🐸, 🐯, 🦝]



[🦊, 🐻, 🐼, 🐸, 🐯, 🦝].slice(2);

// returns slice

// [🐼, 🐸, 🐯, 🦝] - first 2 animals ignored



[🦊, 🐻, 🐼, 🐸, 🐯, 🦝].slice(1, 3);

// [ ... -> 🐻] - starting position - element 1

// (included)


// [ ... <- 🐸 ...] - ending position element 3

//  (not included)


// returns slice

// [🐻, 🐼]
```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)

**Parameters**

- `start`: The starting point from which the slicing begins. The start **is included** in the slice.
- `end`: The position that the slicing stops. The end position **is not included** in the slice.

(Remember, the new array is a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) of the source one).

## Array.prototype.some()
**When to choose this**: When you are checking if at least one element of an array passes a specific condition.
**Returns**: `true` or `false`

```javascript
[🦊, 🐻, 🐼].some(element => element === 🐼);

// true



[🐻, 🐻, 🐻].some(element => element === 🐼);

// false

```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)

If you want to check if all elements pass the condition, you should check `.every` method.

## Array.prototype.sort()
**When to choose this**: When you want to sort the elements in a specific way.
**Returns**: The **source array** sorted.

```javascript
[3, 2, 1].sort();

// [1, 2, 3]



['A', 'C', 'B'].sort();

// ['A', 'B', 'C'] 



[
  { id: 13 },
  
  { id: 42 },
  
  { id: 10 }
  
].sort((itemA, itemB) => itemA.id - itemB.id);

// Result [{ id: 10 }, { id: 13 }, { id: 42 }]
```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

## Array.prototype.splice()
**When to choose this**: When you want to replace some contents of an array or remove them.
**Returns**: **A new array** is created by the removed/replaced elements.

```javascript
[🦊, 🐻, 🐼, 🐸, 🐯, 🦝].splice();

// [🦊, 🐻, 🐼, 🐸, 🐯, 🦝] - source array

// [] - returns empty array



[🦊, 🐻, 🐼, 🐸, 🐯, 🦝].splice(2);

// [🦊, 🐻] - source array

// [🐼, 🐸, 🐯, 🦝] - new array



[🦊, 🐻, 🐼, 🐸, 🐯, 🦝].splice(2, 1);

// [🦊, 🐻, 🐸, 🐯, 🦝] - source array

// [] - returns empty array



[🦊, 🐻, 🐼, 🐸, 🐯, 🐯].splice(2, 0, 🦝, 🦝);

// [🦊, 🐻, 🐸, 🦝, 🦝, 🐯, 🐯] - source array

// [] - new array

/*
   New array was not created
   
   since we asked for 0 deletion.
   
   Instead the source array was modified.
 
 */ 
```
[MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)

**Parameters**

- `start`: The starting point from which the removing/replacing begins. The start **is included** in the slice.
- `count`: How many elements to delete. If omitted, it will be set from the starting position till the end of the array.
- `replacement`: New element(s) to be added from the starting position

(Remember, the new array is a [shallow copy](https://developer.mozilla.org/en-US/docs/Glossary/Shallow_copy) of the source one).

## Guidance on using Javascript array methods

You don’t have to memorize every Javascript array method, its syntax, and its exact functionality! It’s more important to know that they exist. Over time, you’ll naturally develop muscle memory for the ones you use frequently. For the less used methods, just keep them in mind and look them up when needed. Consider bookmarking this post for future reference! 🤓

In this post, we tried to explain/demonstrate some of the most common Javascript array methods. Our intention was not to provide comprehensive documentation, so we intentionally omitted more advanced parameters that are applicable to some of the methods described.

If you’re interested in learning about these less frequently used parameters, we recommend visiting the MDN Documentation linked in the footer of each code snippet.

This post [Javascript Array Methods – Easy Examples That Make Learning A Blast
](https://noghostsinside.com/javascript-array-methods-easy-examples-that-make-learning-a-blast/?utm_source=devto&utm_medium=referral&utm_campaign=republished_content&utm_content=post_url
) was originally published on the [No Ghosts Inside](https://noghostsinside.com/?utm_source=devto&utm_medium=referral&utm_campaign=republished_content&utm_content=post_home_url
) tech blog.