There are iterable and non-iterable objects in JS. If the object contains Symbol.iterator()
function then it's iterable. If the object doesn't contain this function, then it's non-iterable. Why? This function returns iterator object.
So, what the difference between keys()
, values()
, entries()
and Symbol.iterator()
? Looks like they both return iterator objects.
CodePudding user response:
Properties like entries
, keys
, and values
are there for convenience. They allow easy iteration over the content of the Map instance. Note also from the image you posted that entries
is also the value of the Symbol.iterator
property.
The Symbol.iterator
property is present so that code like
for (entry of someMap)
will behave the same as
for (entry of someMap.entries())
The .keys()
and .values()
methods allow iterating over one part of the Map instance or the other, in situations where you only care about the keys, or only about the values. Clearly .entries()
would allow that as well, via deconstructing assignment or simple array indexing.
Ultimately, there are often no satisfactory fundamental answers to questions like "why does language x do this?" or "why does API x do this?" because they're things designed by people who had their own reasons.