JavaScript Tutorials

JavaScript Array values()
Syntax & Examples

Array.values() method

The values() method of the Array class in JavaScript returns a new array iterator object that contains the values for each index in the array.


Syntax of Array.values()

The syntax of Array.values() method is:

values()

This values() method of Array returns a new array iterator object that contains the values for each index in the array.

Return Type

Array.values() returns value of type Array Iterator.



✐ Examples

1 Using values() method to iterate over array values

In JavaScript, we can use the values() method to iterate over array values.

For example,

  1. We define an array variable arr with elements [1, 2, 3, 4, 5].
  2. We use the values() method on arr to get an iterator object containing the values.
  3. We use a for...of loop to iterate over the values in the iterator object.
  4. We log each value to the console using console.log() method.

JavaScript Program

const arr = [1, 2, 3, 4, 5];
const valuesIterator = arr.values();
for (const value of valuesIterator) {
  console.log(value);
}

Output

1
2
3
4
5

2 Using values() method on an array of strings

We can also use the values() method on an array of strings to iterate over string values.

For example,

  1. We define a string array variable strArr with elements ['apple', 'banana', 'cherry', 'date'].
  2. We use the values() method on strArr to get an iterator object containing the string values.
  3. We use a for...of loop to iterate over the string values in the iterator object.
  4. We log each string value to the console using console.log() method.

JavaScript Program

const strArr = ['apple', 'banana', 'cherry', 'date'];
const valuesIterator = strArr.values();
for (const value of valuesIterator) {
  console.log(value);
}

Output

apple
banana
cherry
date

Summary

In this JavaScript tutorial, we learned about values() method of Array: the syntax and few working examples with output and detailed explanation for each example.