Arrays in JavaScript consist of a list of elements. JavaScript has many useful built-in methods, which we will review in this article.

In order to get the most out of this tutorial, you should have some familiarity with creating, indexing, modifying, and looping through arrays, which you can review in the tutorial Understanding Arrays in JavaScript.

Arrays are similar to strings, in that they both consist of a sequence of elements that can be accessed via index number. However, it is important to remember that strings are an immutable datatype, meaning they cannot be changed. Arrays, on the other hand, are mutable, which means that many array methods will affect the original array, not a copy of the array.

Methods that modify the original array are known as mutator methods, and methods that return a new value or representation are known as accessor methods.

In this article, we will learn about adding and removing elements, reversing, replacing, merging and otherwise modifying elements in an array.

Note: Array methods are properly written out as Array.prototype.method(), as Array.prototype refers to the Array object itself. For simplicity, we will simply list the name as method().

Accessor Methods

concat()

The concat() method merges two or more arrays together to form a new array. It does not mutate or affect any of the original arrays.

In the below example, we will create two arrays of types of shellfish and combine them into one new array.

// Create arrays of monovalves and bivalves
let monovalves = ['abalone', 'conch']
let bivalves = ['oyster', 'mussel', 'clam']

// Concatenate them together into shellfish variable
let shellfish = monovalves.concat(bivalves)

shellfish
[ 'abalone', 'conch', 'oyster', 'mussel', 'clam' ]

The concat() method can take multiple arguments, effectively allowing you to concatenate many arrays together with a single method.

#javascript #fundamentals #programming

How To Use Array Methods in JavaScript: Mutator Methods
1.50 GEEK