Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Tip: Converting JavaScript Array-like Objects to Real Arrays

DZone's Guide to

Quick Tip: Converting JavaScript Array-like Objects to Real Arrays

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

JavaScript includes many array-like objects and collections like the arguments object and NodeList. Those objects aren’t real JavaScript arrays, but they can be converted into real arrays very easily. The way to do that is to use the Array.prototype.slice function.

Using Array.prototype.slice to Convert Array-like Objects to Real Arrays

The Array.prototype.slice function returns a shallow copy of a portion of an array. It receives two parameters: the starting index and the end index, which are used as start and end points in the slice. For example, the following code will slice and return a new array out of a numbers array:

var numbers = [1, 2, 3, 4, 5];
var copy = numbers.slice(1, 3);
console.log(copy); // [2,3]

The Array.prototype.slice function can also be used to convert array-like objects and collections to real JavaScript arrays. The following code will convert the arguments object into a real array:

var argsArray = Array.prototype.slice.call(arguments); 

Or:

var argsArray = [].slice.call(arguments); 

Summary

Sometimes while coding, we want to use array-like objects and collections as real arrays. The Array.prototype.slice function can help us to do that.



Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}