The values function generates a fresh array iterator object that contains the values assigned to each index of the array. We can traverse the elements of the array using loops or various iterator techniques.
Syntax
array.values();
Parameter
It does not hold any parameter as such.
Return
It generates and provides a newly instantiated array iterator object.
JavaScript Array values Method Example
Let's discuss some examples to understand better.
Example1
Below is an illustration that utilizes the for...of loop for implementation.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr = ["John","Mary","Tom","Harry","Sheero"]; //Intializing array elements
var itr = arr.values(); //Using values() method.
document.write("The array elements are:<br>");
for (let x of itr) {
document.write("<br>"+x);
} //This iterates the array elements through its index value.
</script>
</body>
</html>
Output:
Subsequent to the iteration, the components of the array are depicted as follows:
Example2
An alternative approach to implementing the array values method utilizing a for...of loop.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
const arr=["P","Q","R","S","T"]; //Initializing array elements.
const itr=arr.values();
document.write("The array elements are: <br>");
for(let x of itr)
{
document.write("<br>"+x);
} //This loop will iterate and print the array elements.
</script>
</body>
</html>
Output:
The output is shown below:
Example3
An example implemented using next method.
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr=["John","Tom","Sheero","Romy","Tomy"]; //Initialized array
var itr=arr.values();
document.write("The array elements are: <br>");
document.write("<br>"+itr.next().value);
document.write("<br>"+itr.next().value);
document.write("<br>"+itr.next().value);
document.write("<br>"+itr.next().value);
document.write("<br>"+itr.next().value);
</script>
</body>
</html>
Output:
Note: If the next method use exceeds the given array length, it will return an 'undefined' value.
Let's understand through an example:
Example
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr=["John","Tom","Sheero","Romy","Tomy"]; //Initialized array
var itr=arr.values();
document.write("The array elements are: <br>");
document.write("<br>"+itr.next().value); //returns value at index 0.
document.write("<br>"+itr.next().value); //returns value at index 1
document.write("<br>"+itr.next().value); //returns value at index 2
document.write("<br>"+itr.next().value); //returns value at index 3
document.write("<br>"+itr.next().value); //returns value at index 4
document.write("<br>"+itr.next().value); //returns undefined
</script>
</body>
</html>
Output:
It is evident that the array's size was set to 4, specifically arr[4]. However, the next method was invoked a total of 5 times. Consequently, the final invocation of next produced an 'undefined' result.