Array.values()
The Array.values()
method in JavaScript returns a new array iterator object that contains the values for each index in the array. It is useful when you want to iterate over the values of an array, especially in conjunction with loops.
Syntax
array.values()
Parameters
The Array.values()
method does not take any parameters.
Return Value
The values()
method returns a new array iterator object containing the values of the array in their original order.
Examples
1. Using values()
with a for...of
Loop
This example demonstrates how to use the values()
method with a for...of
loop to iterate through an array’s values.
const array = [10, 20, 30];
const iterator = array.values();
for (const value of iterator) {
console.log(value);
}
Output
10
20
30
The for...of
loop iterates over the values returned by the values()
method.
2. Accessing Values Using next()
Each call to the next()
method of the iterator returns the next value of the array.
const array = [10, 20, 30];
const iterator = array.values();
console.log(iterator.next().value); // 10
console.log(iterator.next().value); // 20
console.log(iterator.next().value); // 30
console.log(iterator.next().value); // undefined
Output
10
20
30
undefined
After the last value, the next()
method returns undefined
.
3. Using values()
with Sparse Arrays
The values()
method includes undefined
for sparse elements in an array.
const sparseArray = [10, , 30];
const iterator = sparseArray.values();
for (const value of iterator) {
console.log(value);
}
Output
10
undefined
30
The second element in the array is empty, so undefined
is included in the iteration.
4. Combining values()
with Other Methods
You can combine values()
with Array.from()
to create a new array from the iterator.
const array = [1, 2, 3];
const iterator = array.values();
const newArray = Array.from(iterator);
console.log(newArray);
Output
[1, 2, 3]
The Array.from()
method converts the iterator back into an array.