0

Bootstrap 5 Javascript examples sometimes show code like:

var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'))

Why isn't this just:

var collapseElementList = document.querySelectorAll('.collapse')

What is [].slice.call() doing exactly? I don't understand why you'd slice on an empty array, and then I have no idea what call is doing there. What would be the problem with the obvious way to do this, the second way above?

jrochkind
  • 22,799
  • 12
  • 59
  • 74

2 Answers2

2

querySelectorAll returns a NodeList, which is a collection, but not an array.

[].slice.call turns an array-like collection into an array proper. It will allow you to use array methodss on it, eg:

var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'));
const textsOfCollapsedElements = collapseElementList.map(elm => elm.textContent);

Otherwise, if you don't convert it to an array first, you won't be able to use array methods on it.

It's probably most important for forEach. Newer browsers support NodeList.prototype.forEach, but it hasn't been with us that long. In contrast, Array.prototype.forEach has existed forever. So turning the collection into an array allows for forEach to be called on it, even on obsolete browsers that don't support NodeList.prototype.forEach.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

It's an idiom for turning anything array-ish (in this case a DOM NodeList) into a real Array by exploiting the fact that Array::slice can work on anything that's iterable and has a .length property.

The modern idiom is Array.from(...).

AKX
  • 152,115
  • 15
  • 115
  • 172