JavaScript Array values() Method
Last Updated :
04 Dec, 2024
Improve
JavaScript array.values() is an inbuilt method in JavaScript that is used to return a new array Iterator object that contains the values for each index in the array i.e., it prints all the elements of the array.
// Create an array
const fruits = ['Apple', 'Banana', 'Cherry'];
// Use the values() method to get an iterator
const iterator = fruits.values();
// Use a for...of loop to iterate over the values
for (let value of iterator) {
console.log(value);
}
Output
Apple Banana Cherry
Syntax
arr.values();
Return Value
- It returns a new array iterator object i.e., elements of the given array.
Example 1: Printing values of array using array values() method.
// Input array contain some elements
let A = ['Ram', 'Z', 'k', 'geeksforgeeks'];
// Here array.values() method is called.
let iterator = A.values();
// All the elements of the array the array
// is being printed
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
Output
Ram Z k geeksforgeeks
Explanation
- The
values()
method is called on the arrayA
. - An iterator object
iterator
is obtained from the array. - Each call to
iterator.next()
returns an object with avalue
property containing the next element in the array. - The
value
property of each iterator’s result object is logged to the console to print each element of the array sequentially.
Example 2: Array values() method with for loop.
// Input array contain some elements.
let array = ['a', 'gfg', 'c', 'n'];
// Here array.values() method is called.
let iterator = array.values();
// Here all the elements of the array is being printed.
for (let elements of iterator) {
console.log(elements);
}
Output
a gfg c n
Explanation
- The array
array
contains elements'a'
,'gfg'
,'c'
, and'n'
. - An iterator
iterator
is obtained from the array using thevalues()
method. - The
for...of
loop iterates over the elements returned by the iterator. - Each element
elements
is logged to the console. - The output will be
'a'
,'gfg'
,'c'
, and'n'
.
Example 3: Printing elements of array with holes using array values() method.
let array = ["A", "B", , "C", "D"];
let iterator = array.values();
for (let value of iterator) {
console.log(value);
}
Output
A B undefined C D
Explanation
- The array
array
contains elements"A"
,"B"
, an empty slot,"C"
, and"D"
. - An iterator
iterator
is obtained from the array using thevalues()
method. - The
for...of
loop iterates over the elements returned by the iterator. - Each element
value
is logged to the console. - The output will be
"A"
,"B"
,"C"
, and"D"
. The empty slot will not produce any output.
We have a complete list of JavaScript Array methods, to check those please go through this Javascript Array Complete reference article.