JavaScript
Article

Preparing for ECMAScript 6: New Array Methods

By Aurelio De Rosa

As developers, we constantly need to keep up with the latest technologies (that’s why you read SitePoint, right?). If you’re a JavaScript developer, it’s your responsibility to understand the features introduced in new versions of the language. The next version, known as ECMAScript 6, or Harmony, has been under development for a few years. As of August 2014, it has been stabilized. This means that no new features will be added to the specification. It will be completed around the end of 2014, and will start to go into the official publication process starting in March 2015, but things are stable enough to start learning the new methods right now.

In this article we’ll discuss most of the new methods available in ECMAScript 6 that work with the Array type. When discussing them, you’ll note that 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. Keep in mind that because these methods are very recent, the examples will work only in a few browsers. 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(arryLike);

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;
   });
}

var 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 as a JSFiddle.

This method is currently only supported in Firefox 32+, so if you want to employ it you need a polyfill. 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) 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 is more than one element in the array that will return a truthy value, only the first is returned.

An example usage is shown below:

var arr = [1, 2, 3, 4];
var 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 as a JSFiddle.

This method has slightly better support, as it’s implemented in Firefox 25+, and Chrome 35+ and Opera 22+ behind a flag (“Enable Experimental JavaScript”). 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.

var arr = [1, 2, 3, 4];
var 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 as a JSFiddle.

This method is supported by Firefox 25+, and Chrome 35+ and Opera 22+ behind a flag (“Enable Experimental JavaScript”). A polyfill for this method 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:

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

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

A live demo is shown below and also available as a JSFiddle.

Array.prototype.keys() is supported by Firefox 28+, and Chrome 35+ and Opera 22+ behind a flag.

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:

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

// prints "1, 2, 3, 4", one at a time, because the 
// array contains these four elements
var 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 as a JSFiddle.

The Array.prototype.values() method is supported by Chrome 35+ and Opera 22+ behind the usual flag.

Array.prototype.fill()

If you have worked in the PHP world (like me), you will recall a function named array_fill() that was missing in JavaScript. In ECMAScript 6 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:

var 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 as a JSFiddle.

This method is currently supported in Firefox 31+, and Chrome 37+ and Opera 24+ behind the usual flag. 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 ECMAScript 6 that work with arrays. Whether you find them useful or not, they are on their way. It’s clear that these methods aren’t really ready for the prime time, but you still should keep an eye on them. Of course there is more in ECMAScript 6 than what we’ve described in this article as we’ll discover in the upcoming ones.

  • tomseldon

    Thanks for the article. :) One minor correction though: In your `Array.from` example, I’m pretty sure 2×2 is 4, not 3. ;)

    • Aurelio De Rosa

      lol…of course is 4. Thanks for the comment and for spotting the typo.

  • Craig Buckler

    Nice! from() will finally allow us to convert node collections to real arrays without any slicing nonsense!

    • callmenick1

      Same thing I thought, so useful.

    • Aurelio De Rosa

      I agree with you Craig.

  • callmenick1

    Array.prototype.findIndex() is a winner!

  • armando hinojosa

    In your Array.from() example, you take “arguments” as the 1st parameter, shouldn’t it be “arr” instead?

  • Francisc

    `Array.method()` is not a good way to shorten `Array.prototype.method()`.
    It’s better to use `Array#method()` instead.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.