Javascript Array Methods – Easy Examples That Make Learning A Blast

Avatar photo

By George

8 min read
Bookmark this post

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


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

// false



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

// true
MDN Documentation

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.


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

// [🦊, 🐻]

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

// []
MDN Documentation

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

When a method returns a new array, it is not 100% independent from its source array. It’s a shallow 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.


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

// 🐼



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

// 🐼 (The first one)

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

// undefined
MDN Documentation

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.


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

// [🐻, 🐻, 🐻]



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

// default level is 1

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



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

// Infinity will flatten all levels

// [🐻, 🐻, 🐼, 🦊, 🐻, 🦊]
MDN Documentation

(Remember, the new array is a shallow 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


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

// undefined
MDN Documentation

Callback params

  1. element – the element of each iteration
  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.

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


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

// true



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

// false
MDN Documentation

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


[{ 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.


[🦊, 🐻, 🐼].length;

// 3



[].length;

// 0
MDN Documentation

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.


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

 id: index, animalIcon: element

}));


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

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.


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

// 🐼



[].pop();

// undefined
MDN Documentation

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.


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

// returns 4

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



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

// returns 6

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

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.


[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 Documentation

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.


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

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

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.


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

// 🦊



[].shift();

// undefined
MDN Documentation

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.


[🦊, 🐻, 🐼, 🐸, 🐯, 🦝].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 Documentation

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 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


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

// true



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

// false
MDN Documentation

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.


[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 Documentation

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.

[🦊, 🐻, 🐼, 🐸, 🐯, 🦝].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 Documentation

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 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.

DigitalOcean Referral Badge
guest
0 Comments
Inline Feedbacks
View all comments

Continue reading

Front, Programming

What You Need to Know About CSS nth child Selector – A Practical Guide

Front, Programming

Learn How to Select Only the CSS First Child

Front, Programming

Grayscale Backdrop Filter: A Useful Tool To Make Grayish Backgrounds

Front, Programming

How To Calculate CSS Line Height

Front, Programming

Coding Made Easy With CSS Selectors: An Ultimate Guide

Front, Programming

Most Useful HTML Elements for Maximizing Better Results

Front, Programming

CSS Box Sizing – Better Implementations, Less Headaches

Front, Programming

What Is the CSS Box Model in Simple Terms

Front, Programming

CSS Text Decoration In Action: A Powerful Guide

Front, Programming

HTML Formatting Elements Made Simple: With Easy And Practical Examples

Front, Programming

How To Be Creative With Different CSS Border Styles

Front, Programming

How To Work With CSS Syntax: The Correct Way!

Subscribe to our newsletter

Dive into the Fun Side of Tech! Posts, News, and More Delivered to Your Inbox!

Intuit Mailchimp