ES6 in Action: New Array.* and Array.prototype.* Methods

Share this article

New ES6 Array Methods

In this article we’ll discuss most of the new methods available in ES6 that work with the Array type, using Array.* and Array.prototype.*.

When discussing them, I’ll write Array.method() when I describe a “class” method and Array.prototype.method() when I outline an “instance” method.

We’ll also see some example uses and mention several polyfills for them. If you need a polyfill-them-all library, you can use es6-shim by Paul Miller.

Array.from()

The first method I want to mention is Array.from(). It creates a new Array instance from an array-like or an iterable object. This method can be used to solve an old problem with array-like objects that most developers solve using this code:

// typically arrayLike is arguments
var arr = [].slice.call(arrayLike);

The syntax of Array.from() is shown below:

Array.from(arrayLike[, mapFn[, thisArg]])

The meaning of its parameters are:

  • arrayLike: an array-like or an iterable object
  • mapFn: a function to call on every element contained
  • thisArg: a value to use as the context (this) of the mapFn function.

Now that we know its syntax and its parameters, let’s see this method in action. In the code below we’re going to create a function that accepts a variable number of arguments, and returns an array containing these elements doubled:

function double(arr) {
  return Array.from(arguments, function(elem) {
    return elem * 2;
  });
}

const result = double(1, 2, 3, 4);

// prints [2, 4, 6, 8]
console.log(result);

A live demo of the previous code is shown below and also available at JSBin.

ES6 in Action: New Array Methods on jsbin.com

This method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, there are a couple of polyfills to choose from: one is available on the method’s page on MDN, while the other has been written by Mathias Bynens and is called Array.from.

Array.prototype.find()

Another of the methods introduced is Array.prototype.find(). The syntax of this method is:

Array.prototype.find(callback[, thisArg])

As you can see, it accepts a callback function used to test the elements of the array and an optional argument to set the context (this value) of the callback function. The callback function receives three parameters:

  • element: the current element
  • index: the index of the current element
  • array: the array you used to invoke the method.

This method returns a value in the array if it satisfies the provided callback function, or undefined otherwise. The callback is executed once for each element in the array until it finds one where a truthy value is returned. If there’s more than one element in the array, that will return a truthy value, and only the first is returned.

An example usage is shown below:

const arr = [1, 2, 3, 4];
const result = arr.find(function(elem) { return elem > 2; });

// prints "3" because it’s the first
// element greater than 2
console.log(result);

A live demo of the previous code is shown below and also available at JSBin.

ES6 in Action: New Array Methods on jsbin.com

The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need a polyfill, one is provided on the method’s page on MDN.

Array.prototype.findIndex()

A method that is very similar to the previous one is Array.prototype.findIndex(). It accepts the same arguments but instead of returning the first element that satisfies the callback function, it returns its index. If none of the elements return a truthy value, -1 is returned. An example usage of this method is shown below:

const arr = [1, 2, 3, 4];
const result = arr.findIndex(function(elem) {return elem > 2;});

// prints "2" because is the index of the
// first element greater than 2
console.log(result);

A live demo of the previous code is shown below and also available at JSBin.

ES6 in Action: New Array Methods on jsbin.com

The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need a polyfill, one can be found on the method’s page on MDN.

Array.prototype.keys()

Yet another method introduced in this new version of JavaScript is Array.prototype.keys(). This method returns a new Array Iterator (not an array) containing the keys of the array’s values. We’ll cover array iterators in an upcoming article, but if you want to learn more about them now, you can refer to the specifications or the MDN page.

The syntax of Array.prototype.keys() is shown below:

Array.prototype.keys()

An example of use is the following:

const arr = [1, 2, 3, 4];
const iterator = arr.keys();

// prints "0, 1, 2, 3", one at a time, because the
// array contains four elements and these are their indexes
let index = iterator.next();
while(!index.done) {
  console.log(index.value);
  index = iterator.next();
}

A live demo is shown below and also available at JSBin.

ES6 in Action: New Array Methods on jsbin.com

Array.prototype.keys() in Node and all modern browsers, with the exception of Internet Explorer.

Array.prototype.values()

In the same way we can retrieve the keys of an array, we can retrieve its values using Array.prototype.values(). This method is similar to Array.prototype.keys() but the difference is that it returns an Array Iterator containing the values of the array.

The syntax of this method is shown below:

Array.prototype.values()

An example use is shown below:

const arr = [1, 2, 3, 4];
const iterator = arr.values();

// prints "1, 2, 3, 4", one at a time, because the
// array contains these four elements
let index = iterator.next();
while(!index.done) {
  console.log(index.value);
  index = iterator.next();
}

A live demo of the previous code is shown below and also available at JSBin.

ES6 in Action: New Array Methods on jsbin.com

The Array.prototype.values() is currently not implemented in most browsers. In order for you to use it you need to transpile it via Babel.

Array.prototype.fill()

If you’ve worked in the PHP world (like me), you’ll recall a function named array_fill() that was missing in JavaScript. In ES6 this method is no longer missing. Array.prototype.fill() fills an array with a specified value optionally from a start index to an end index (not included).

The syntax of this method is the following:

Array.prototype.fill(value[, start[, end]])

The default values for start and end are respectively 0 and the length of the array. These parameters can also be negative. If start or end are negative, the positions are calculated starting from the end of the array.

An example of use of this method is shown below:

const arr = new Array(6);
// This statement fills positions from 0 to 2
arr.fill(1, 0, 3);
// This statement fills positions from 3 up to the end of the array
arr.fill(2, 3);

// prints [1, 1, 1, 2, 2, 2]
console.log(arr);

A live demo of the previous code is shown below and also available at JSBin.

ES6 in Action: New Array Methods on jsbin.com

The method is supported in Node and all modern browsers, with the exception of Internet Explorer. As polyfills you can employ the one on the method’s page on MDN, or the polyfill developed by Addy Osmani.

Conclusion

In this article we’ve discussed several of the new methods introduced in ES6 that work with arrays. With the exception of Array.prototype.values(), they enjoy good browser support and can be used today!

Frequently Asked Questions about ES6 Array Methods

What are the new ES6 Array Methods?

ES6, also known as ECMAScript 2015, introduced several new methods for the Array prototype. These include find(), findIndex(), fill(), and copyWithin(). The find() method returns the first element in the array that satisfies a provided testing function. The findIndex() method, on the other hand, returns the index of the first element in the array that satisfies the testing function. The fill() method changes all elements in an array to a static value, from a start index to an end index. Lastly, the copyWithin() method shallow copies part of an array to another location in the same array and returns it, without modifying its size.

How does the find() method work in ES6?

The find() method in ES6 is used to find the first element in an array that satisfies a provided testing function. It executes the function once for each index in the array until it finds one where the function returns a truthy value. If such an element is found, find() immediately returns the value of that element. Otherwise, it returns undefined. Here’s an example:

let array = [5, 12, 8, 130, 44];
let found = array.find(element => element > 10);
console.log(found);
// expected output: 12

What is the difference between find() and findIndex() methods in ES6?

Both find() and findIndex() methods in ES6 are used to find an element in an array that satisfies a provided testing function. The key difference between the two is what they return. The find() method returns the first element that satisfies the testing function, while findIndex() returns the index of the first element that satisfies the testing function. If no element satisfies the testing function, find() returns undefined, and findIndex() returns -1.

How can I use the fill() method in ES6?

The fill() method in ES6 changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array. Here’s an example:

let array = [1, 2, 3, 4];
console.log(array.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

What does the copyWithin() method do in ES6?

The copyWithin() method in ES6 shallow copies part of an array to another location in the same array and returns it, without modifying its size. It takes three arguments: target (the index at which to copy the sequence to), start (the index at which to start copying elements from), and end (the index at which to end copying elements from). Here’s an example:

let array = ['a', 'b', 'c', 'd', 'e'];
console.log(array.copyWithin(0, 3, 4));
// expected output: ["d", "b", "c", "d", "e"]

Can I use ES6 Array Methods in all browsers?

While most modern browsers support ES6 Array Methods, some older versions of browsers may not support them. You can check the compatibility table on the Mozilla Developer Network (MDN) for detailed browser support information. If you need to support older browsers, you may need to use polyfills or transpilers like Babel.

How can I test if an element exists in an array using ES6 Array Methods?

You can use the find() or findIndex() methods to test if an element exists in an array. If the find() method returns a value other than undefined, or if the findIndex() method returns an index other than -1, the element exists in the array.

Can I modify the original array with ES6 Array Methods?

Yes, some ES6 Array Methods like fill() and copyWithin() modify the original array. However, methods like find() and findIndex() do not modify the original array.

How can I remove an element from an array using ES6 Array Methods?

ES6 does not introduce a specific method for removing elements from an array. However, you can use the splice() method, which is available in earlier versions of JavaScript, to remove elements from an array.

Can I use ES6 Array Methods with other data types like strings or objects?

Yes, some ES6 Array Methods can be used with other data types. For example, the find() and findIndex() methods can be used with arrays of strings or objects. However, methods like fill() and copyWithin() are specifically designed for arrays.

Aurelio De RosaAurelio De Rosa
View Author

I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.

array methodsColinIECMAScript6harmonylearn-modernjsmodernjsmodernjs-hub
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form