Array-like objects in JavaScript


Do you know what the difference between following two snippets are? Why are we in first case calling map function on array but than at second we call map it as prototype.map.call method which exists on function object (almost everything in JavaScript is an object).

var numbers = [1,2,3,4]

var multipliedBy3 = numbers.map(function(number) {
    return number * 3
})
var links = document.getElementsByTagName('a')

var urls = Array.prototype.map.call(links, function(link) {
    return link.href
})

Well, the answer is in fact that in second case we are not working with array, but array-like object. This is an object with keys as numbers which act as indices. In practise we get them with DOM properties and methods which returns list of items (document.getElementById, document.forms, …) or with automatically created variable arguments in functions. We can use all array functions on this array-like object but they must be called in a way where we specify this array-like object to be a context (this) for an array function.

We can also convert this array-like objects to array as such

links = Array.prototype.slice(links)

In ES6 syntax you can also use following alternative

links = Array.from(links)