JavaScript Array values() method


The values() method in JavaScript is used to create a new array iterator object that contains the values of each element in an array. This method is useful when you need to iterate over the values of an array without needing their corresponding keys (indices).

Syntax:

let arrayIterator = array.values();

Return Value:

  • A new Array Iterator object that contains the values of the array.

Key Points:

  • The values() method does not modify the original array.
  • The resulting iterator can be traversed using methods like next(), or it can be used in a loop (such as a for...of loop) to iterate over the values.

Example 1: Basic usage

let array = ['a', 'b', 'c']; let iterator = array.values(); console.log(iterator.next().value); // 'a' console.log(iterator.next().value); // 'b' console.log(iterator.next().value); // 'c'

Example 2: Using a for...of loop

You can easily iterate over the values using a for...of loop:

let array = ['x', 'y', 'z']; for (let value of array.values()) { console.log(value); } // Output: // 'x' // 'y' // 'z'

Example 3: Converting to an Array

If you want to convert the iterator into an array of values, you can use Array.from():

let array = [10, 20, 30]; let valuesArray = Array.from(array.values()); console.log(valuesArray); // [10, 20, 30]

Example 4: Nested Arrays

The values() method can be used with nested arrays as well:

let nestedArray = [[1, 2], [3, 4], [5, 6]]; let iterator = nestedArray.values(); for (let value of iterator) { console.log(value); } // Output: // [1, 2] // [3, 4] // [5, 6]

Summary:

  • The values() method provides a convenient way to access the values of elements in an array without needing their indices.
  • It returns an iterator, allowing for flexible iteration over the values in various contexts, such as loops and transformations.
  • This method is particularly useful for scenarios where you only need the values from an array, simplifying code and enhancing readability.