JavaScript Reference ยท Array
Array.prototype.values()
Reference for JavaScript Array.prototype.values(): get an iterator over the elements of an array, how it relates to for...of and Symbol.iterator, and its quirks.
The values() method returns a new array iterator object that yields each element of the array, from index 0 to the end. It is the method that for...of, spread and destructuring use behind the scenes: Array.prototype[Symbol.iterator] is the very same function.
You rarely call values() yourself for plain loops, because for (const x of array) does it for you. It is useful when you want an iterator object to pass around, to pull items one at a time with next(), or to use alongside keys() and entries().
const it = ["a", "b"].values(); it.next(); // { value: "a", done: false }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.values()
Parameters: none.
Return value: a new array iterator. Each call to next() returns { value, done }. After the last element, done is true and value is undefined.
Exceptions: none for real arrays.
Usage notes
- Same as the default iteration.
for (const x of arr)and[...arr]usearr[Symbol.iterator](), which isvalues(). - The iterator is live. It reads the array as it goes, so elements added before the iterator reaches the end are included. It does not take a snapshot.
- Holes are visited. The iterator yields
undefinedfor empty slots, unlikeforEach()orObject.keys(), which skip them. - One pass only. An iterator that has finished stays finished. Call
values()again for a fresh one. - Iterators are iterable. The returned object has its own
[Symbol.iterator]()that returns itself, so it works infor...ofand spread. - Iterator helpers. Current engines add methods like
map(),filter()andtake()to iterators, soarr.values().map(fn)is lazy and returns an iterator rather than an array. These helpers are recent; check a compatibility table. - Related iterators:
keys()yields indexes andentries()yields[index, value]pairs. - Typed arrays,
MapandSethave their ownvalues()methods with the same shape.
Browser support
Array.prototype.values() works in all current browsers and in Node.js; it arrived after the older array methods, so very old browsers lack it. Iterator helper methods on the returned object are newer still.