JavaScript Array values()

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

The syntax of the values() method is:

arr.values()

Here, arr is an array.


values() Parameters

The values() method does not have any parameters.


Return value from values()

  • Returns a new Array iterator object.

Notes:

  • The values() method does not change the original array.
  • The values() method does not ignore empty array elements.

Example: Using values() method

const languages = ["JavaScript", "Java", , "C++", "Python", "Lua"];
let iterator = languages.values();

// using .next() with iterator object
console.log(iterator.next()); // { value: 'JavaScript', done: false }

console.log(iterator.next().value); // Java

console.log("Remaining:")

for (let value of iterator) {
  console.log(value);
}

console.log(iterator.next()) // { value: undefined, done: true }

Output

{ value: 'JavaScript', done: false }
Java
Remaining:
undefined
C++
Python
Lua
{ value: undefined, done: true }

The for..of loops ends when next().done = true or currentIndex > length. So, we get value as undefined after printing all values.

Also, the empty value is not ignored and is displayed as undefined.


Recommended Reading: JavaScript Array keys()