JavaScript Array values()

The values() method returns a new Array Iterator object that contains the values for each index in the array.

Example


values() Syntax

The syntax of the values() method is:

arr.values()

Here, arr is an array.


values() Parameters

The values() method does not take any parameters.


values() Return Value

  • Returns a new Array iterator object.

Notes: The value() method does not change the original array.


Example 1: Using values() Method

Output

A
B
C

In the above example, we have used the value() method to access the values for each index in the languages array.

We have called the method as languages.values() which returns an array iterator object i.e. iteratorObject.

Using for..of, we have then looped through iteratorObject that prints values of each index of the array.

Note: We can also use the next().value with the array iterator object to access the values. The following code prints the first value in the array.

console.log(iteratorObject.next().value); 

Example 2: Using values() in Arrays with Holes

The values() method does not ignore holes in the array. It returns undefined for empty slots in the array.

Output

A
B
undefined
C

Here we have called the values() method in the array that has empty slots.

Since there is an empty slot in the third index of arrayWithHole, the method returns undefined as a value for that index.


Example 3: More About Array Iterator Object

The array iterator object does not store values rather it stores the address of the array used. For example:

Output

Apple
Cherry

In the above example, we have changed the value of index 1 of the fruits array.

So on changing the value in the array, iteratorObject returns the new value i.e ('Cherry') stored at index 1.


Recommended Reading: JavaScript Array keys()