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

August 20, 2013

no comments

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

JavaScript includes many array-like objects/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 using 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:  starting index and 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/collections to real JavaScript arrays. The following code will convert the arguments object into a real array:

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


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


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

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>