JavaScript Array values()

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

Example

let languages = ["JavaScript", "Java", "C++"];

// returns an Array Iterator object that contain values let iteratorObject = languages.values();
// looping through iterator for (let value of iteratorObject) { console.log(value); } // Output: // JavaScript // Java // C++

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

let languages = ["A", "B", "C"];

// returns an iterator object that contain values of languages let iteratorObject = languages.values();
// looping through iterator for (let value of iteratorObject) { console.log(value); }

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.

let arrayWithHole = ["A", "B", , "C"];

// returns 'undefined' as a value for empty slot let iteratorObject = arrayWithHole.values();
// looping through iterator for (let value of iteratorObject) { console.log(value); }

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:

let fruits = ["Apple", "Banana", "Grapes"];

// returns values of each index in the fruits array let iteratorObject = fruits.values();
// accessing the value of index 0 in the array console.log(iteratorObject.next().value); // Apple // changing the value of index 1 fruits[1] = "Cherry"; // accessing the value of index 1 in the array console.log(iteratorObject.next().value); // Cherry

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()