ES6 brings us many new features, one that has recently been implemented in Firefox 32 is the new
Array.from method. This method allows you to convert an array like object to an array.
Array like object?
But what is an array-like object exactly? And more importantly, how can this benefit me?
The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:
var args = Array.prototype.slice.call(arguments);
The above example works, but is difficult to remember and not very readable.
Converting arguments using Array.from
Instead of the ES5
slice approach for converting arguments to an array, we can use the ES6
Array.from method instead:
var args = Array.from(arguments);
I'm sure you'll agree this method is more readable and definitely easier to remember.
So that's just one use-case for
Array.from. There are many more interesting uses for this new feature. Please check out the MDN page for more examples.
If you have any useful examples that you'd like to share then please get in touch as I'd love to hear them.