querySelectorAll() returns a what?

I’m taking the JavaScript Certification and am pretty frustrated trying to understand the definitions in the “What Is the querySelectorAll() Method, and When Should You Use It?” lesson.

Fairly straightforward in its first mention:

querySelectorAll() returns a NodeList object, a collection of nodes that match the specified CSS selector.”

OK. It returns an Object.

But later in the same page, the example says:


const matches = document.querySelectorAll("ul.ingredients li");

This will return a collection of three nodes. Each node represents a list item element:

// NodeList(3)
{
  0: `<li>Flour</li>`,
  1: `<li>Cheese</li>`,
  2: `<li>Water</li>`,
  length: 3,
}

You can work with this collection exactly like you would work with any other JavaScript array.


So it’s a collection. But also an array, because “any other JavaScript array” implicitly includes this collection in the definition of “array”. And the structure looks like what I’d use to declare an object (a non-array object).

The quiz at the end says the querySelectorAll() does not return an array. The correct answer, NodeList, well, fair enough. That is defined within the lesson. But it seems incomplete to me. NodeLists are objects, and collections, but not arrays, that can be used exactly like arrays?

Taking '“object” as the superset of collections and arrays clears up that stage, but I do not understand exactly what a collection is, and why an object that works exactly like an array is not an array.

Can anyone point me in the right direction for some definition?

under the hood arrays are objects, they are special objects that have ordered numerical property names, and a length property. With this consideration a NodeList is array-like because it has numerical properties and a length and you can access the elements with arr[0] and arr[1] etc

Thanks for this. I’ve been down a bit of a rabbit hole; this post

https://stackoverflow.com/questions/29707568/javascript-difference-between-array-and-array-like-object

Helped too.

The notion of an array-like object makes perfect sense to me. I remain hung up on the “exactly like any other JavaScript array”. Every reference I find for array-likes, including the stack overflow post above, indicate at least some difference is expected.

Either the use of “exactly” is a minor editing error in the lesson, or I have a major misunderstanding of the difference between array and array-like.

it is not exactly an array, it does not have array methods for example (but a forEach for NodeLists exist)

Thank you for helping make FCC better. Bugs can be reported as GitHub Issues. Whenever reporting a bug, please check first that there isn’t already an issue for it and provide as much detail as possible.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.