Skip to content
Tutorials Center
My learning

Topics

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().

JavaScript
const it = ["a", "b"].values();
it.next(); // { value: "a", done: false }

Try it

JS Stepping through an iterator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Live view and holes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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] use arr[Symbol.iterator](), which is values().
  • 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 undefined for empty slots, unlike forEach() or Object.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 in for...of and spread.
  • Iterator helpers. Current engines add methods like map(), filter() and take() to iterators, so arr.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 and entries() yields [index, value] pairs.
  • Typed arrays, Map and Set have their own values() 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.